import requests
import datetime
from datetime import date
import json
import re
import keys
proxy_url = ""
country_code = "it"
language_code = "it"
time_offset = 120
noLinearChannels = True  # set True if you don't want to get Linear Channels
pin = "0000"  # pin to get 18+ channels


def getChannels():
    try:
        headers = {
            'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
            'Content-Type': 'application/json',
            'X-DAZN-UA': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 signin/4.30.0.42 hyper/0.8.4 (web; production; gb)',
            'Z-DAZN-UA': 'bWFkZSBieSB0aGUgY29tbXVuaXR5IGF0IGRybXNjcmlwdHMuY29t',
            'Cache-Control': 'no-cache',
            'Referer': 'https://www.dazn.com/',
            'sec-ch-ua-platform': '"Windows"',
        }

        json_data = {
            'Email': 'lcdsrn@gmail.com',
            'Password': 'Tiamonapoli1926',
            'Platform': 'web',
            'DeviceId': '0000000000',
            'ProfilingSessionId': '0000000000000000000000',
        }

        if proxy_url:
            proxies = {
                'http': proxy_url,
                'https': proxy_url
            }
        else:
            proxies = None

        try:
            with open("authorisationToken.txt") as ftoken:
                authorisationToken = ftoken.read()
                ftoken.close()
        except FileNotFoundError:
            with requests.post('https://authentication-prod.ar.indazn.com/v5/SignIn', headers=headers, json=json_data, proxies=proxies) as responseData:
                response = responseData
            data = response.json()
            authorisationToken = data.get("AuthToken", {}).get("Token")

            if authorisationToken:
                with open("authorisationToken.txt", "w") as f:
                    f.write(authorisationToken)
            else:
                print('LOGIN FAILED')
                exit()

        today = date.today()
        url = f"https://epg.discovery.indazn.com/eu/v2/Epg?date={today.year}-{today.month:02d}-{today.day:02d}&country={country_code}&languageCode={language_code}&openBrowse=false&timeZoneOffset={time_offset}"

        with requests.get(url) as responseData:
            response = responseData
        data = response.json()
        assetid_list = []

        output = []
        for tile in data.get('Tiles', []):
            VideoType = tile.get('VideoType')
            IsLinear = tile.get('IsLinear')
            competition = tile.get('Competition', [{}]).get("Id")
            LaUrl = data.get("PlaybackDetails", [{}])[0].get("LaUrl")
            if ((noLinearChannels and VideoType == "Live" and not IsLinear) or (not noLinearChannels and VideoType == "Live")):
                canali = {}
                canali['asset_id'] = tile.get('AssetId')
                canali['start'] = tile.get('Start')
                canali['end'] = tile.get('End')
                canali['imageurl'] = f"https://image.discovery.indazn.com/jp/v3/jp/none/{tile['Image']['Id']}/fill/center/top/none/85/1920/1083/webp/image"
                output.append(canali)

        channels = []
        count = 1
        for channel in output:
            params = {
                'AssetId': '%s' % channel['asset_id'],
                'PlayerId': 'test',
                'DrmType': 'WIDEVINE',
                'Platform': 'web',
                'Format': 'MPEG-DASH',
                'LanguageCode': 'it',
                'Model': 'N/A',
                'Secure': 'true',
                'Latitude': 'null',
                'Longitude': 'null',
                'Manufacturer': 'unknown',
                'PlayReadyInitiator': 'false',
                'MtaLanguageCode': 'en',
                'AppVersion': '9.29.0',
            }

            headers = {
                'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
                'Referer': 'https://www.dazn.com/',
                'sec-ch-ua-mobile': '?0',
                'Authorization': 'Bearer %s' % authorisationToken,
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
                'x-dazn-device': '00000000-0000-0000-0000-000000000000',
                'sec-ch-ua-platform': '"Windows"',
                'x-age-verification-pin': pin,
            }

            with requests.get('https://api.playback.indazn.com/v5/Playback', params=params, headers=headers, proxies=proxies) as responseData:
                response = responseData

            if response.status_code == 401:
                headers_refresh = {
                    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0',
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer %s' % authorisationToken,
                }
                json_data_refresh = {
                    'DeviceId': '0000000000'
                }
                with requests.post('https://ott-authz-bff-prod.ar.indazn.com/v5/RefreshAccessToken', headers=headers_refresh, json=json_data_refresh, proxies=proxies) as responseData:
                    response_refresh = responseData
                data_refresh = response_refresh.json()
                authorisationToken = data_refresh.get("AuthToken", {}).get("Token")
                with open("authorisationToken.txt", "w") as f:
                    f.write(authorisationToken)
                headers = {
                    'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
                    'Referer': 'https://www.dazn.com/',
                    'sec-ch-ua-mobile': '?0',
                    'Authorization': 'Bearer %s' % authorisationToken,
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
                    'x-dazn-device': '00000000-0000-0000-0000-000000000000',
                    'sec-ch-ua-platform': '"Windows"',
                    'x-age-verification-pin': pin,
                }
                with requests.get('https://api.playback.indazn.com/v5/Playback', params=params, headers=headers, proxies=proxies) as responseData:
                    response = responseData

            if response.status_code == 200:
                data = response.json()
                manifestUrl = replace_links(data.get("PlaybackDetails", [{}])[0].get("ManifestUrl"))
                LaUrl = replace_links(data.get("PlaybackDetails", [{}])[0].get("LaUrl"))


                eventTitle = data.get("Asset", {}).get("Title")
                kid_key = keys.getKeys(manifestUrl, LaUrl, authorisationToken)
                canale = {
                    "Id": str(count),
                    "Name": eventTitle,
                    "mpdUrl": manifestUrl,
                    "startDate": channel['start'],
                    "endDate": channel['end'],
                    "imageurl": channel['imageurl'],
                    "kid": kid_key.split(":")[0],
                    "key": kid_key.split(":")[1]
                }
                channels.append(canale)
                count += 1

        # Scrivi l'output nel file output.json
        with open("outputorig.json", 'w+') as f:
            json.dump(channels, f, indent=2)

        # Controlla e sostituisci i link nel nuovo file output1.json
        channels_with_replaced_links = []
        for channel in channels:
            channel_copy = channel.copy()
            channel_copy['mpdUrl'] = replace_links(channel_copy['mpdUrl'])
            channels_with_replaced_links.append(channel_copy)

        with open("output.json", 'w+') as f:
            json.dump(channels_with_replaced_links, f, indent=2)

    except Exception as e:
        print("An error occurred:", str(e))

# Esegui la funzione
getChannels()
