import requests
import json
import os
from urllib.parse import urlsplit
import shutil

# Headers
headers = {
    'authority': 'graphql.ott.sky.com',
    'accept': '*/*',
    'accept-language': 'en-GB,en;q=0.9,en-US;q=0.8',
    'dnt': '1',
    'origin': 'https://www.nowtv.it',
    'referer': 'https://www.nowtv.it/',
    'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Microsoft Edge";v="120"',
    '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/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
    'x-skyott-device': 'COMPUTER',
    'x-skyott-language': 'it',
    'x-skyott-platform': 'PC',
    'x-skyott-proposition': 'NOWTV',
    'x-skyott-provider': 'NOWTV',
    'x-skyott-territory': 'IT',
}

# Funzione per scaricare l'immagine
def download_image(image_url, folder_path):
    # Creare il nome del file a partire dall'URL
    image_name = os.path.basename(urlsplit(image_url).path)
    image_path = os.path.join(folder_path, image_name)
    
    # Scarica l'immagine e salvala
    with requests.get(image_url) as img_response:
        if img_response.status_code == 200:
            with open(image_path, 'wb') as f:
                f.write(img_response.content)
    return image_path

# Pulisci la cartella Sports se esiste
if os.path.exists('Sports'):
    shutil.rmtree('Sports')  # Rimuove la cartella e tutto il suo contenuto

# Crea di nuovo la cartella Sports
os.makedirs('Sports', exist_ok=True)

# Elimina il file Sports.json se esiste
if os.path.exists('Sports.json'):
    os.remove('Sports.json')

# Richiesta API
response = requests.get(f'https://graphql.ott.sky.com/graphql?extensions=%7B%22persistedQuery%22:%7B%22version%22:1,%22sha256Hash%22:%22cd5f7877654195bcb0ee18a491b29cb3dfc608d7b0df3d0e09b821bb5957b6f9%22%7D%7D&variables=%7B%22sectionNavigation%22:%22sports%22,%22formatType%22:%22SD%22,%22defaultFormat%22:%22SD%22%7D', headers=headers)

# Ottieni i dati in formato JSON
jsondata = response.json()

# Prepara la collezione di canali
collection = list()

# Itera sui canali
for i, channel in enumerate(jsondata['data']['linearChannels']):
    channeljson = {
        'id': channel['name'],
        'channel_id': channel['id'],
        'channel_name': channel['name'],
        'channel_logo': channel['logos'][0]['template'].format(width=100, height=100),
        'live': {},
        'next': {},
    }

    # Gestione immagine live
    if channel['now']['imageUrl']:
        channeljson['live']['imageUrl'] = download_image(channel['now']['imageUrl'], 'Sports')
    else:
        channeljson['live']['imageUrl'] = None
    
    channeljson['live']['title'] = channel['now']['title']
    
    # Gestione immagine next
    if channel['next']['imageUrl']:
        channeljson['next']['imageUrl'] = download_image(channel['next']['imageUrl'], 'Sports')
    else:
        channeljson['next']['imageUrl'] = None
    
    channeljson['next']['title'] = channel['next']['title']
    
    # Aggiungi il canale alla collezione
    collection.append(channeljson)

# Stampa per debug
print(collection)

# Scrivi il risultato su un file JSON
with open('Sports.json', 'w+') as f:
    json.dump(collection, f, indent=2)
