import requests
import json
import os

# Headers per la richiesta
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',
}

# IP locale per la path delle immagini
local_ip = "195.54.160.184"

# Percorso principale per salvare le immagini
base_dir = "sports"
os.makedirs(base_dir, exist_ok=True)

# Funzione per formattare i nomi delle cartelle senza spazi
def format_folder_name(name):
    return name.replace(" ", "_").replace("/", "_")

# Funzione per sanificare stringhe problematiche
def sanitize(value):
    if isinstance(value, str):
        return value.encode('utf-8', errors='ignore').decode('utf-8')
    return value if value else None

# Funzione per scaricare immagini in modo sicuro
def download_image(url, path):
    try:
        print(f"Downloading: {url} to {path}")
        response = requests.get(url, headers=headers, stream=True)
        if response.status_code == 200:
            with open(path, "wb") as img_file:
                for chunk in response.iter_content(1024):
                    img_file.write(chunk)
        else:
            print(f"Errore HTTP {response.status_code} per {url}")
    except Exception as e:
        print(f"Errore durante il download di {url}: {e}")

# Richiesta HTTP per ottenere i dati
response = requests.get(
    '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
)
jsondata = response.json()

# Raccolta dati e download immagini
collection = []
for i, channel in enumerate(jsondata['data']['linearChannels']):
    try:
        # Nome canale
        channel_name = format_folder_name(channel['name'])
        channel_dir = os.path.join(base_dir, channel_name)
        os.makedirs(channel_dir, exist_ok=True)

        # Costruzione dati del canale
        channeljson = {
            'id': sanitize(channel_name),
            'channel_id': sanitize(channel['id']),
            'channel_name': sanitize(channel['name']),
            'channel_logo': None,
            'live': {},
            'next': {},
        }

        # Scarica e salva il logo del canale
        logo_url = channel['logos'][0]['template'].format(width=100, height=100)
        logo_path = os.path.join(channel_dir, "logo.jpg")
        download_image(logo_url, logo_path)
        channeljson['channel_logo'] = f"http://{local_ip}/{logo_path.replace(os.sep, '/')}"

        # Aggiunta immagini live e next
        for key in ['now', 'next']:
            if channel[key]:
                image_url = channel[key]['imageUrl'][:-4] if channel[key]['imageUrl'] else None
                title = sanitize(channel[key]['title'])
                channeljson[key] = {'title': title, 'imageUrl': None}
                if image_url:
                    image_path = os.path.join(channel_dir, f"{key}.jpg")
                    download_image(image_url, image_path)
                    channeljson[key]['imageUrl'] = f"http://{local_ip}/{image_path.replace(os.sep, '/')}"
        collection.append(channeljson)

    except Exception as e:
        print(f"Errore nel canale {i}: {channel}")
        print(f"Errore: {e}")

# Salva i dati in un file JSON
try:
    with open('Sports.json', 'w', encoding='utf-8') as f:
        json.dump(collection, f, indent=2, ensure_ascii=False)
    print("File JSON salvato con successo.")
except Exception as e:
    print(f"Errore durante il salvataggio del file JSON: {e}")

print("Download completato e JSON aggiornato con percorsi locali delle immagini.")
