import requests
import datetime
from datetime import date
import json
import re
import keys

proxy_url = None
country_code = "it"
language_code = "it"
time_offset = 60
noLinearChannels = True  # set True if you don't want get Linear Channels
pin = ""  # pin to get 18+ channels


def getChannels():

   headers = {
      "sec-ch-ua": '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
      "sec-ch-ua-mobile": "?0",
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.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/113.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()
   #   print(data)
   #   return
   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"
            )
            # print(canali)
            output.append(canali)

   #   print(output)
   channels = []
   count = 1
   for channel in output:
      headers = {
         'accept': '*/*',
         'accept-language': 'en-GB,en;q=0.9,en-US;q=0.8,it-IT;q=0.7,it;q=0.6',
         'authorization': f'Bearer {authorisationToken}',
         'dnt': '1',
         'origin': 'https://www.dazn.com',
         'priority': 'u=1, i',
         'referer': 'https://www.dazn.com/',
         'sec-ch-ua': '"Microsoft Edge";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
         'sec-ch-ua-mobile': '?0',
         'sec-ch-ua-platform': '"Windows"',
         'sec-fetch-dest': 'empty',
         'sec-fetch-mode': 'cors',
         'sec-fetch-site': 'cross-site',
         'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0',
         'x-correlation-id': 'd06275a2-4349-4fdd-80f6-fbc9d1de6056',
         'x-dazn-device': '0223712e-33fa-4ba2-99fa-204ee5731a21',
      }

      response =  requests.get(
            f"https://api.playback.indazn.com/v5/Playback?AppVersion=0.38.2&DrmType=WIDEVINE&Format=MPEG-DASH&PlayerId=%40dazn%2Fpeng-html5-core%2Fweb%2Fweb&Platform=web&LanguageCode=en&Model=unknown&Secure=true&Manufacturer=microsoft&PlayReadyInitiator=false&Capabilities=mta&AssetId={channel["asset_id"]}&MtaLanguageCode",
            headers=headers,
            proxies=proxies,
      )

      # print(response.status_code)

      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 = {
               'accept': '*/*',
               'accept-language': 'en-GB,en;q=0.9,en-US;q=0.8,it-IT;q=0.7,it;q=0.6',
               'authorization': f'Bearer {authorisationToken}',
               'dnt': '1',
               'origin': 'https://www.dazn.com',
               'priority': 'u=1, i',
               'referer': 'https://www.dazn.com/',
               'sec-ch-ua': '"Microsoft Edge";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
               'sec-ch-ua-mobile': '?0',
               'sec-ch-ua-platform': '"Windows"',
               'sec-fetch-dest': 'empty',
               'sec-fetch-mode': 'cors',
               'sec-fetch-site': 'cross-site',
               'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0',
               'x-correlation-id': 'd06275a2-4349-4fdd-80f6-fbc9d1de6056',
               'x-dazn-device': '0223712e-33fa-4ba2-99fa-204ee5731a21',
            }

            response =  requests.get(
                  f"https://api.playback.indazn.com/v5/Playback?AppVersion=0.38.2&DrmType=WIDEVINE&Format=MPEG-DASH&PlayerId=%40dazn%2Fpeng-html5-core%2Fweb%2Fweb&Platform=web&LanguageCode=en&Model=unknown&Secure=true&Manufacturer=microsoft&PlayReadyInitiator=false&Capabilities=mta&AssetId={channel["asset_id"]}&MtaLanguageCode",
                  headers=headers,
                  proxies=proxies,
            )

      if response.status_code == 200:
            data = response.json()
            # print(json.dumps(data, indent=2))
            cdnToken = manifestUrl = data.get("PlaybackDetails", [{}])[0]["CdnToken"]["Value"]
            manifestUrl = data.get("PlaybackDetails", [{}])[0].get("ManifestUrl")
            manifestUrl += f"&dazn-token={cdnToken}"
            LaUrl = data.get("PlaybackDetails", [{}])[0].get("LaUrl")
            eventTitle = data.get("Asset", {}).get("Title")
            # print("Askinggg kid key PPPPPPPPPPPPPP")
            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
   return json.dumps(channels)


json_data = getChannels()
data = json.loads(json_data)
with open("output.json", "w+") as f:
    json.dump(data, f, indent=2)

for item in data:
    name = item.get("Name", "")
    mpd_url = item.get("mpdUrl", "")
    # imageurl = item.get("imageurl", "")
    # keys = item.get("keys", "")
    print(f"{name}\n{mpd_url}")
    # print(f"{name}\n{mpd_url}&decryption_key={keys}")
