from flask import Blueprint, redirect, request
import requests

itv_bp = Blueprint('itv', __name__)

@itv_bp.route('/itvx')
def itvredirect():
    channel = request.args.get('channel', 'ITV')

    proxies = {
        'http': 'http://localhost:8080',
        'https': 'http://localhost:8080',
    }

    cookies = {
        'SyrenisCookieFormConsent_Itv.Session': '{"tokens":{"content":{"entitlement":{"purchased":[],"source":"","failed_availability_checks":[]},"email_verified":true,"token_type":"bearer","missingUserData":["NoPlanSelected"]}}',
    }

    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:126.0) Gecko/20100101 Firefox/126.0',
        'Accept': 'application/vnd.itv.online.playlist.sim.v3+json',
        'Accept-Language': 'en-GB,en;q=0.5',
        'Referer': 'https://www.itv.com/',
        'Origin': 'https://www.itv.com',
        'DNT': '1',
        'Connection': 'keep-alive',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'no-cors',
        'Sec-Fetch-Site': 'same-site',
        'Priority': 'u=4',
        'Pragma': 'no-cache',
        'Cache-Control': 'no-cache',
        'Content-Type': 'application/x-www-form-urlencoded',
    }

    data = '{"user":{"itvUserId":"{4f129513-1f5b-4dc9-8a2a-b6434e93c938}","entitlements":[],"profile_id":"{4f129513-1f5b-4dc9-8a2a-b6434e93c938}_0"},"device":{"manufacturer":"Firefox","model":"126.0","os":{"name":"Mac OS","version":"10.15","type":"desktop"}},"client":{"version":"4.1","id":"browser","supportsAdPods":true,"service":"itv.x","appversion":"2.228.2"},"variantAvailability":{"player":"dash","featureset":{"min":["mpeg-dash","widevine"],"max":["mpeg-dash","widevine"]},"platformTag":"dotcom"}}'

    response = requests.post(
        f'https://simulcast.itv.com/playlist/itvonline/{channel}',
        cookies=cookies,
        headers=headers,
        data=data,
        proxies=proxies,
    ).json()

    url = response['Playlist']['Video']['VideoLocations'][0]['Url']
    return redirect(url)
