import time
import json
import urllib.request
from datetime import datetime, timezone, timedelta

URL = "https://hodor.prod.front.tim.cptech.pro/api/v2/timvision/page/af409439167c926e46953739179fc285/110435.json?aegon=true&epgIds=90099000%2C90200132%2C90200130%2C90200131%2C90300133%2C90320074%2C90100897%2C90100475%2C90120081%2C90300553%2C90100567%2C90020075%2C90020062%2C90120088%2C90100896%2C90020037%2C90120080%2C90100721%2C90120077%2C90120078%2C90100895%2C90020076%2C90100603%2C90020061%2C90020060%2C90200642%2C90020020%2C90020000%2C90020001%2C90020002%2C90020003%2C90020004%2C90020005%2C90020019%2C90020021&get=200&featureToggles=detailLight"
HEADERS = {'User-Agent': 'Mozilla/5.0'}
OUTPUT_FILE = "eurosport_epg.json"

# Fuso orario italiano (UTC+2) per i timestamp
tz_italy = timezone(timedelta(hours=2))

def fetch_data():
    req = urllib.request.Request(URL, headers=HEADERS)
    with urllib.request.urlopen(req) as response:
        return json.loads(response.read().decode('utf-8'))

def generate_epg():
    print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Aggiornamento EPG Eurosport in corso...")
    try:
        data = fetch_data()
        epg_list = []
        
        now_ts = datetime.now(tz_italy).timestamp()

        for channel in data.get('channels', []):
            channel_name = channel.get('Name', '')
            for prog in channel.get('contents', []):
                title = prog.get('title', '')
                if not title:
                    continue
                
                # Elaborazione date (da millisecondi a secondi)
                start_ts = prog.get('startTime', 0) / 1000
                end_ts = prog.get('endTime', 0) / 1000
                
                # Verifichiamo se il programma è attualmente in onda
                if not (start_ts <= now_ts <= end_ts):
                    continue
                
                # Elaborazione immagine locandina
                image_url = prog.get('URLImage', '')
                if image_url:
                    # Sostituiamo i placeholder per ottenere un'immagine in alta risoluzione
                    image_url = image_url.replace('{resolutionXY}', '1920x1080').replace('{imageQualityPercentage}', '100')
                
                start_dt = datetime.fromtimestamp(start_ts, tz=tz_italy)
                end_dt = datetime.fromtimestamp(end_ts, tz=tz_italy)
                
                start_str = start_dt.isoformat(timespec='seconds')
                end_str = end_dt.isoformat(timespec='seconds')
                
                epg_item = {
                    "title": title,
                    "image": image_url,
                    "channel": channel_name,
                    "start": start_str,
                    "end": end_str
                }
                
                # Aggiunta di descrizione (sottotitolo) e categoria se presenti
                subtitle = prog.get('subtitle')
                if subtitle:
                    epg_item['description'] = subtitle
                    
                category = prog.get('subgenre') or prog.get('genre')
                if category:
                    epg_item['category'] = category

                epg_list.append(epg_item)
                
        with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
            json.dump(epg_list, f, indent=2, ensure_ascii=False)
            
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] EPG aggiornato con successo: trovati {len(epg_list)} programmi.")
    except Exception as e:
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Errore durante l'aggiornamento: {e}")

def main():
    print("Avvio del Bot EPG Eurosport. L'aggiornamento avverrà ogni minuto.")
    while True:
        generate_epg()
        # Attesa di 60 secondi prima del prossimo aggiornamento
        time.sleep(60)

if __name__ == "__main__":
    main()
