from helpers.signature_generator import *
from helpers.get_pssh import *
from helpers.decrypt import *
import requests
import hashlib
import json
import os

currentFile = __file__
realPath = os.path.realpath(currentFile)
dirPath = os.path.dirname(realPath)
dirName = os.path.basename(dirPath)
keys_file = dirPath + '/nowtv.json'

def load_channels(file_path='channel.txt'):
    channels = []
    with open(file_path, 'r') as f:
        for line in f:
            if 'serviceKey:' in line and 'channelTitle:' in line:
                parts = line.strip().split('|')
                service_key = parts[0].split(':', 1)[1].strip()
                channel_title = parts[1].split(':', 1)[1].strip()
                channels.append((service_key, channel_title))
    return channels

def get_token(skyCEsidismesso01):
    headers = {
        'Accept': 'application/vnd.tokens.v1+json',
        'Content-Type': 'application/vnd.tokens.v1+json',
        'User-Agent': 'okhttp/4.11.0',
        'X-SkyOTT-Device': "TV",
        'X-SkyOTT-Platform': "ANDROIDTV",
        'X-SkyOTT-Proposition': 'NOWOTT',
        'X-SkyOTT-Provider': 'NOWTV',
        'X-SkyOTT-Territory': "GB",
    }

    data = {
        'auth': {
            'authScheme': 'SSO',
            'authIssuer': 'NOWTV',
            'provider': 'NOWTV',
            'providerTerritory': "GB",
            'proposition': 'NOWOTT',
            'authToken': skyCEsidismesso01,
        },
        'device': {
            'type': "TV",
            'platform': "ANDROIDTV",
            'id': "On03Ow6Ulj1rXLuqGfKC",
            'drmDeviceId': 'UNKNOWN'
        }
    }

    headers['Content-MD5'] = hashlib.md5(json.dumps(data).encode()).hexdigest()
    token_request = requests.post('https://auth.client.ott.sky.com/auth/tokens', headers=headers, json=data, proxies=proxies)
    return token_request.json().get("userToken", "")

def get_resources(serviceKey):
    headers = {
        'Content-Type': 'application/vnd.playlive.v1+json',
        'User-Agent': 'okhttp/4.11.0',
        'x-skyott-usertoken': token,
        'x-skyott-territory': 'GB',
        'x-skyott-provider': 'NOWTV',
        'x-skyott-pinoverride': 'true',
        'x-skyott-proposition': 'NOWOTT',
        'x-skyott-device': 'TV',
        'x-skyott-platform': 'ANDROIDTV'
    }

    payload = {
        "serviceKey": serviceKey,
        "parentalControlPin": None,
        "personaParentalControlRating": "5",
        "device": {
            "capabilities": [
                {
                    "protection": "PLAYREADY",
                    "container": "ISOBMFF",
                    "transport": "DASH",
                    "acodec": "EAC3",
                    "vcodec": "H265",
                    "colourSpace": "HDR10",
                },
                {
                    "protection": "PLAYREADY",
                    "container": "ISOBMFF",
                    "transport": "DASH",
                    "acodec": "AAC",
                    "vcodec": "H265",
                    "colourSpace": "HDR10",
                },
                {
                    "protection": "PLAYREADY",
                    "container": "ISOBMFF",
                    "transport": "DASH",
                    "acodec": "EAC3",
                    "vcodec": "H264",
                    "colourSpace": "SDR",
                },
                {
                    "protection": "PLAYREADY",
                    "container": "ISOBMFF",
                    "transport": "DASH",
                    "acodec": "AAC",
                    "vcodec": "H264",
                    "colourSpace": "SDR",
                }
            ],
            "maxVideoFormat": "HD",
            "model": "ANDROIDTV",
            "hdcpEnabled": 'false',
            "supportedColourSpaces": ["DV", "HDR10", "SDR"]
        },
        "client": {
            "thirdParties": [
                "CONVIVA",
                "FREEWHEEL",
                "MEDIATAILOR",
                "FRV4"
            ]
        }
    }

    signature, timestamp = get_signature("POST", "https://ovp.nowtv.com/video/playouts/live", headers=headers, payload=payload)
    headers["x-sky-signature"] = f'SkyOTT client="IE-NOWTV-ANDROID-v1",signature="{signature}",timestamp="{timestamp}",version="1.0"'

    resources_req = requests.post("https://ovp.nowtv.com/video/playouts/live", headers=headers, json=payload, proxies=proxies)
    resources_req.raise_for_status()
    resources = resources_req.json()

    channel = {
        "mpd": resources.get("asset", {}).get("endpoints", [{}])[0].get("url", ""),
        "license_url": resources.get("protection", {}).get("licenceAcquisitionUrl", ""),
        "pssh": get_pssh(resources.get("asset", {}).get("endpoints", [{}])[0].get("url", ""))
    }
    return channel

def main():
    with open("config.json", "r") as f:
        config = json.load(f)

    global proxies
    global token
    proxies = config["proxies"]
    token = get_token(config["skyCEsidismesso01"])

    channels = load_channels("channel.txt")
    all_channel_data = []

    for service_key, channel_title in channels:
        try:
            channel_resources = get_resources(service_key)
        except Exception as e:
            print(f"Error fetching data for serviceKey {service_key}: {e}")
            continue

        mpd = channel_resources["mpd"]
        pssh_list = channel_resources["pssh"]
        license_url = channel_resources["license_url"]

        print(f"channelTitle: {channel_title}")
        print(f"Service Key: {service_key}")
        print("MPD:", mpd)
        print("\n")

        keys = []
        if pssh_list:
            print("Key(s):\n")
            seen_keys = set()
            for p in pssh_list:
                try:
                    decrypted_keys = decrypt(license_url, p, proxies)
                    for key in decrypted_keys:
                        if key not in seen_keys:
                            print(key)
                            seen_keys.add(key)
                            keys.append(key)
                except Exception as de:
                    print(f"Error decrypting PSSH: {de}")

        channel_data = {
            "channelTitle": channel_title,
            "serviceKey": service_key,
            "mpd": mpd,
            "keys": keys
        }

        all_channel_data.append(channel_data)
        print("\n" + "-" * 60 + "\n")

    # Save everything to response.json
    with open("response.json", "w") as outfile:
        json.dump(all_channel_data, outfile, indent=4)
        print("✅ Response data written to response.json")

if __name__ == "__main__":
    main()
