"""
EPG Bot per WarnerBros Discovery - v3
Genera un EPG JSON con locandine reali dei programmi (16:9).

Fonti immagini (in ordine di priorità):
1. Discovery+ warnermediacdn (da discovery_images_db.json)
2. TMDB backdrop_path (16:9, 1920x1080)
3. Stringa vuota (MAI loghi canale)
"""
import urllib.request
import urllib.parse
import gzip
import xml.etree.ElementTree as ET
import json
import logging
import re
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import os
import time
import random

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

ROME_TZ = ZoneInfo("Europe/Rome")

OUTPUT_FILE = "discovery_epg.json"
XMLTV_URL = "http://epg-guide.com/it.gz"
XMLTV_CACHE_FILE = "it.gz"
IMAGE_DB_FILE = "discovery_images_db.json"       # Immagini warnermediacdn (scraping Discovery+)
IMAGE_CACHE_FILE = "discovery_images_cache.json"  # Cache TMDB lookups

TMDB_API_KEY = "e9e9d8da18ae29fc430845952232787c"

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"
)

# Canali WarnerBros Discovery target
TARGET_CHANNELS = {
    "Nove": "Nove",
    "Real Time": "Real Time",
    "Food Network": "Food Network",
    "DMAX": "DMAX",
    "HGTV": "HGTV",
    "Motor Trend": "Motor Trend",
    "K2": "K2",
    "Frisbee": "Frisbee",
    "Giallo": "Giallo"
}

# ============================================================
# Image Database (warnermediacdn)
# ============================================================
wbd_images = {}   # titolo_lowercase -> URL warnermediacdn
tmdb_cache = {}   # titolo_lowercase -> URL tmdb (o "" se non trovato)

def load_wbd_images():
    """Carica il database di immagini warnermediacdn da discovery_images_db.json"""
    global wbd_images
    if os.path.exists(IMAGE_DB_FILE):
        try:
            with open(IMAGE_DB_FILE, 'r', encoding='utf-8') as f:
                raw_db = json.load(f)
            
            wbd_images = {}
            for k, v in raw_db.items():
                wbd_images[k] = v
                # Assicuriamoci che esista anche la versione super-pulita (senza caratteri strani/replacement)
                wbd_images[normalize_title(k)] = v
                
            logger.info(f"Caricate {len(wbd_images)} immagini warnermediacdn dal DB.")
        except Exception as e:
            logger.error(f"Errore caricamento DB immagini: {e}")
            wbd_images = {}

def load_tmdb_cache():
    """Carica la cache TMDB (solo lookup già fatti, MAI loghi canale)."""
    global tmdb_cache
    if os.path.exists(IMAGE_CACHE_FILE):
        try:
            with open(IMAGE_CACHE_FILE, 'r', encoding='utf-8') as f:
                tmdb_cache = json.load(f)
            logger.info(f"Caricati {len(tmdb_cache)} risultati TMDB dalla cache.")
        except Exception:
            tmdb_cache = {}

def save_tmdb_cache():
    """Salva la cache TMDB su disco."""
    try:
        with open(IMAGE_CACHE_FILE, 'w', encoding='utf-8') as f:
            json.dump(tmdb_cache, f, indent=2, ensure_ascii=False)
    except Exception as e:
        logger.error(f"Errore salvataggio cache TMDB: {e}")

def normalize_title(title):
    """Rimuove la parte tra parentesi per ottenere il titolo base del programma."""
    t = title.lower()
    # rimuovi info di stagione/episodio es. (St.1 Ep.4) o [1^TV]
    t = re.sub(r'\(.*?\)', '', t)
    t = re.sub(r'\[.*?\]', '', t)
    t = re.sub(r'st\.\d+', '', t)
    t = re.sub(r'ep\.\d+', '', t)
    t = t.replace('1^tv', '')
    t = t.replace('\ufffd', '')
    # rimuovi caratteri speciali, tieni solo alfanumerici e spazi
    t = re.sub(r'[^\w\s]', '', t)
    return t.strip()

def search_tmdb_backdrop(title):
    """Cerca un backdrop 16:9 su TMDB. Ritorna URL o stringa vuota."""
    try:
        query = urllib.parse.quote(title)
        url = f"https://api.themoviedb.org/3/search/multi?api_key={TMDB_API_KEY}&query={query}&language=it-IT"
        req = urllib.request.Request(url, headers={'User-Agent': USER_AGENT})
        resp = urllib.request.urlopen(req, timeout=10)
        data = json.loads(resp.read())
        
        results = data.get('results', [])
        if results:
            # Preferisci backdrop (16:9)
            backdrop = results[0].get('backdrop_path')
            if backdrop:
                return f"https://image.tmdb.org/t/p/original{backdrop}"
    except Exception:
        pass
    return ""

def get_program_image(title, channel_name=""):
    """
    Cerca la locandina del programma. Ordine di priorita:
    1. Match esatto nel DB warnermediacdn
    2. Match normalizzato (senza parentesi) nel DB warnermediacdn
    3. TMDB backdrop (con cache)
    4. Placeholder specifico del canale (se fornito)
    """
    if not title:
        return ""
    
    title_lower = title.lower().strip()
    title_base = normalize_title(title)
    
    # 1. Match esatto nel DB warnermediacdn
    if title_lower in wbd_images:
        return wbd_images[title_lower]
    
    # 2. Match normalizzato (senza parentesi/episodio)
    if title_base in wbd_images:
        return wbd_images[title_base]
        
    # 2.5 Match parziale (es. "sinceramente persia" in "sinceramente persia one milf show")
    if len(title_base) > 5:
        for db_title, img_url in wbd_images.items():
            if title_base in db_title or db_title in title_base:
                return img_url

    # 3. TMDB (con cache)
    if title_base in tmdb_cache:
        img = tmdb_cache[title_base]
    else:
        # 4. Cerca su TMDB (prima col titolo base, poi col titolo completo)
        img = search_tmdb_backdrop(title_base)
        if not img:
            img = ""
        # Salva in cache TMDB (anche se vuoto, per non ripetere la ricerca)
        tmdb_cache[title_base] = img

    if img:
        return img

    if channel_name:
        placeholders = {
            "Nove": "https://addictedbytheproject.nl/epg_discovery/discovery_placeholder/discovery_nove.png",
            "Real Time": "https://addictedbytheproject.nl/epg_discovery/discovery_placeholder/discovery_realtime.png",
            "Food Network": "https://addictedbytheproject.nl/epg_discovery/discovery_placeholder/discovery_foodnetwork.png",
            "DMAX": "https://addictedbytheproject.nl/epg_discovery/discovery_placeholder/discovery_dmax.png",
            "HGTV": "https://addictedbytheproject.nl/epg_discovery/discovery_placeholder/discovery_hgtv.jpg",
            "Motor Trend": "https://addictedbytheproject.nl/epg_discovery/discovery_placeholder/discovery_mortortrend.png",
            "K2": "https://addictedbytheproject.nl/epg_discovery/discovery_placeholder/discovery_k2.png",
            "Frisbee": "https://addictedbytheproject.nl/epg_discovery/discovery_placeholder/discovery_frisbee.png",
            "Giallo": "https://addictedbytheproject.nl/epg_discovery/discovery_placeholder/discovery_giallo.png"
        }
        return placeholders.get(channel_name, "")
    
    return ""

# ============================================================
# XMLTV Parsing
# ============================================================
def parse_xmltv_date(date_str):
    """Converte le date XMLTV (20260612140000 +0200) in ISO 8601."""
    if not date_str:
        return ""
    try:
        parts = date_str.split(" ")
        time_part = parts[0][:14]
        dt = datetime.strptime(time_part, "%Y%m%d%H%M%S")
        
        offset = parts[1] if len(parts) > 1 else "+0200"
        sign = 1 if offset[0] == '+' else -1
        hours = int(offset[1:3])
        minutes = int(offset[3:5])
        
        dt_utc = dt - timedelta(hours=sign*hours, minutes=sign*minutes)
        dt_utc = dt_utc.replace(tzinfo=ZoneInfo("UTC"))
        return dt_utc.astimezone(ROME_TZ).isoformat()
    except Exception as e:
        logger.error(f"Errore parsing data {date_str}: {e}")
        return ""

def download_xmltv():
    """Scarica il file XMLTV. Se 429, usa la cache locale."""
    logger.info("Download EPG XMLTV in corso...")
    req = urllib.request.Request(XMLTV_URL, headers={'User-Agent': USER_AGENT})
    
    try:
        data = urllib.request.urlopen(req, timeout=30).read()
        with open(XMLTV_CACHE_FILE, "wb") as f:
            f.write(data)
        logger.info(f"XMLTV scaricato ({len(data)} bytes)")
        return data
    except urllib.error.HTTPError as e:
        if e.code == 429:
            logger.warning("429 Too Many Requests - uso cache locale.")
        else:
            logger.error(f"Errore HTTP {e.code}: {e}")
    except Exception as e:
        logger.error(f"Errore download XMLTV: {e}")
    
    # Fallback alla cache locale
    if os.path.exists(XMLTV_CACHE_FILE):
        with open(XMLTV_CACHE_FILE, "rb") as f:
            data = f.read()
        logger.info(f"Usato file XMLTV in cache ({len(data)} bytes)")
        return data
    
    logger.error("Nessun file XMLTV disponibile (né online né in cache).")
    return None

def parse_xmltv(compressed_data):
    """Decomprime e parsa il file XMLTV."""
    try:
        xml_data = gzip.decompress(compressed_data)
        return ET.fromstring(xml_data)
    except Exception as e:
        logger.error(f"Errore decompressione/parsing XMLTV: {e}")
        return None

# ============================================================
# SuperGuidaTV Scraper
# ============================================================
def scrape_superguidatv(url, channel_name):
    """
    Recupera il palinsesto odierno da superguidatv.it
    """
    req = urllib.request.Request(url, headers={'User-Agent': USER_AGENT})
    
    try:
        html = urllib.request.urlopen(req, timeout=15).read().decode('utf-8', errors='ignore')
    except Exception as e:
        logger.error(f"Errore download superguidatv.it per {channel_name}: {e}")
        return []
        
    matches = re.findall(r'>(\d{2}:\d{2})</p>.*?<p class="sgtv-truncate[^>]*>([^<]+)</p>', html)
    events = []
    
    tz = ZoneInfo("Europe/Rome")
    now = datetime.now(tz)
    today_str = now.strftime("%Y-%m-%d")
    tomorrow_str = (now + timedelta(days=1)).strftime("%Y-%m-%d")
    
    programs = []
    for match in matches:
        programs.append((match[0], match[1].strip()))
        
    for i in range(len(programs)):
        start_time, title = programs[i]
        start_hour = int(start_time.split(':')[0])
        
        if i + 1 < len(programs):
            end_time = programs[i+1][0]
        else:
            end_time = "23:59"
            
        end_hour = int(end_time.split(':')[0])
        
        # Gestione giorno
        if start_hour < 6 and now.hour > 18:
            s_date = tomorrow_str
        elif start_hour >= 18 and now.hour < 6:
            s_date = (now - timedelta(days=1)).strftime("%Y-%m-%d")
        else:
            s_date = today_str
            
        if end_hour < start_hour:
            if s_date == today_str:
                e_date = tomorrow_str
            else:
                e_date = today_str
        else:
            e_date = s_date
            
        start_iso = f"{s_date}T{start_time}:00+02:00"
        end_iso = f"{e_date}T{end_time}:00+02:00"
        
        events.append({
            "title": title,
            "image": "",
            "channel": channel_name,
            "channel_number": None,
            "start": start_iso,
            "end": end_iso,
            "description": f"Programmazione {channel_name} (by superguidatv.it)",
            "category": ""
        })
    return events

# ============================================================
# TVEPG Scraper (fallback alternativo)
# ============================================================
def scrape_tvepg(slug, channel_name):
    """
    Recupera il palinsesto odierno da tvepg.eu
    """
    url = f"https://tvepg.eu/it/italy/c/{slug}"
    req = urllib.request.Request(url, headers={'User-Agent': USER_AGENT})
    
    try:
        html = urllib.request.urlopen(req, timeout=15).read().decode('utf-8', errors='ignore')
    except Exception as e:
        logger.error(f"Errore download tvepg.eu per {channel_name}: {e}")
        return []
        
    matches = re.findall(r'title="(\d{2}:\d{2})\s+([^"]+)"', html)
    events = []
    
    tz = ZoneInfo("Europe/Rome")
    now = datetime.now(tz)
    today_str = now.strftime("%Y-%m-%d")
    tomorrow_str = (now + timedelta(days=1)).strftime("%Y-%m-%d")
    
    programs = []
    for match in matches:
        # Tvepg mostra i programmi di oggi (e un po' di domani o ieri)
        programs.append((match[0], match[1].strip()))
        
    for i in range(len(programs)):
        start_time, title = programs[i]
        start_hour = int(start_time.split(':')[0])
        
        if i + 1 < len(programs):
            end_time = programs[i+1][0]
        else:
            end_time = "23:59"
            
        end_hour = int(end_time.split(':')[0])
        
        # Gestione giorno
        if start_hour < 6 and now.hour > 18:
            s_date = tomorrow_str
        elif start_hour >= 18 and now.hour < 6:
            s_date = (now - timedelta(days=1)).strftime("%Y-%m-%d")
        else:
            s_date = today_str
            
        if end_hour < start_hour:
            if s_date == today_str:
                e_date = tomorrow_str
            else:
                e_date = today_str
        else:
            e_date = s_date
            
        start_iso = f"{s_date}T{start_time}:00+02:00"
        end_iso = f"{e_date}T{end_time}:00+02:00"
        
        events.append({
            "title": title,
            "image": "",
            "channel": channel_name,
            "channel_number": None,
            "start": start_iso,
            "end": end_iso,
            "description": f"Programmazione {channel_name} (by tvepg.eu)",
            "category": ""
        })
    return events

# ============================================================
def update_full_epg():
    """Scarica XMLTV, filtra i canali target, cerca le immagini, salva il JSON."""
    logger.info("=== Inizio aggiornamento EPG WarnerBros Discovery ===")
    
    compressed = download_xmltv()
    if not compressed:
        return
    
    root = parse_xmltv(compressed)
    if root is None:
        return
    
    # Mappa channel_id -> nome canale
    channel_map = {}
    for ch in root.findall('channel'):
        dn = ch.find('display-name')
        if dn is not None and dn.text:
            xml_name = dn.text.strip()
            xml_id = ch.attrib.get('id')
            for target_name, expected in TARGET_CHANNELS.items():
                if xml_name.lower() == expected.lower():
                    channel_map[xml_id] = target_name
                    break
    
    logger.info(f"Trovati {len(channel_map)} canali target nel XMLTV.")
    
    events = []
    titles_without_image = set()
    
    for prog in root.findall('programme'):
        ch_id = prog.attrib.get('channel')
        if ch_id not in channel_map:
            continue
        
        ch_name = channel_map[ch_id]
        
        start = parse_xmltv_date(prog.attrib.get('start', ''))
        end = parse_xmltv_date(prog.attrib.get('stop', ''))
        if not start or not end:
            continue
        
        title_el = prog.find('title')
        title = title_el.text if title_el is not None else ""
        
        desc_el = prog.find('desc')
        desc = desc_el.text if desc_el is not None else ""
        
        cat_el = prog.find('category')
        category = cat_el.text if cat_el is not None else ""
        
        # Cerca immagine dal XMLTV stesso (raro ma possibile)
        icon_el = prog.find('icon')
        image = icon_el.attrib.get('src', '') if icon_el is not None else ""
        
        # Se non c'è immagine nel XMLTV, cerca nelle nostre fonti
        if not image:
            image = get_program_image(title, ch_name)
        
        if not image:
            titles_without_image.add(normalize_title(title))
        
        events.append({
            "title": title,
            "image": image,
            "channel": ch_name,
            "channel_number": None,
            "start": start,
            "end": end,
            "description": desc,
            "category": category
        })
    
    # --- INTEGRAZIONE SCRAPER ESTERNI ---
    # Canali mancanti nel file XMLTV ma recuperabili tramite tvepg.eu e tivu.tv
    tvepg_missing = {
        "Motor Trend": "discovery-turbo",
        "K2": "k2",
        "Frisbee": "frisbee"
    }
    
    for missing_ch, slug in tvepg_missing.items():
        logger.info(f"Scraping tvepg.eu per {missing_ch} (Slug: {slug})...")
        tvepg_events = scrape_tvepg(slug, missing_ch)
        
        for ev in tvepg_events:
            image = get_program_image(ev["title"], missing_ch)
            ev["image"] = image
            if not image:
                titles_without_image.add(normalize_title(ev["title"]))
            events.append(ev)

    # HGTV da SuperGuidaTV perché non c'è su tvepg
    sgtv_missing = {
        "HGTV": "https://www.superguidatv.it/programmazione-canale/oggi/guida-programmi-tv-hgtv-homegarden/575/"
    }
    
    for missing_ch, sgtv_url in sgtv_missing.items():
        logger.info(f"Scraping superguidatv.it per {missing_ch}...")
        sgtv_events = scrape_superguidatv(sgtv_url, missing_ch)
        
        for ev in sgtv_events:
            # Assegna l'immagine usando la nostra logica (TMDB/Discovery)
            image = get_program_image(ev["title"], missing_ch)
            ev["image"] = image
            if not image:
                titles_without_image.add(normalize_title(ev["title"]))
            events.append(ev)
            
    # Ordina tutti gli eventi per start date
    events.sort(key=lambda x: x["start"])
    
    # Salva cache TMDB
    save_tmdb_cache()
    
    # Report
    with_img = sum(1 for e in events if e['image'])
    without_img = sum(1 for e in events if not e['image'])
    logger.info(f"Eventi totali: {len(events)} | Con immagine: {with_img} | Senza: {without_img}")
    if titles_without_image:
        logger.info(f"Titoli senza immagine ({len(titles_without_image)}): {', '.join(sorted(titles_without_image)[:10])}...")
    
    # Salva EPG
    output = {
        "timestamp": datetime.now().isoformat(),
        "source": "discovery_epg_bot",
        "total_events": len(events),
        "events": events
    }
    
    with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
        json.dump(output, f, indent=2, ensure_ascii=False)
    
    logger.info(f"EPG salvato in {OUTPUT_FILE}")

def update_live_epg():
    """Legge il discovery_epg.json e crea il file live_epg.json con gli eventi attuali."""
    if not os.path.exists(OUTPUT_FILE):
        return
        
    try:
        with open(OUTPUT_FILE, 'r', encoding='utf-8') as f:
            data = json.load(f)
            events = data.get("events", [])
    except Exception as e:
        logger.error(f"Errore lettura {OUTPUT_FILE} per live EPG: {e}")
        return

    now = datetime.now(ROME_TZ)
    live_events = {}
    
    for e in events:
        try:
            st = datetime.fromisoformat(e["start"])
            en = datetime.fromisoformat(e["end"])
            if st <= now <= en:
                ch = e["channel"]
                # In caso di sovrapposizioni (es. palinsesti errati), prendiamo il primo match o quello più corto
                if ch not in live_events:
                    live_events[ch] = e
                else:
                    # Scegli quello che finisce prima (spesso le guide hanno eventi che racchiudono altri eventi)
                    current_en = datetime.fromisoformat(live_events[ch]["end"])
                    if en < current_en:
                        live_events[ch] = e
        except Exception as exc:
            pass
            
    live_output = {
        "timestamp": now.isoformat(),
        "source": "discovery_epg_bot",
        "live_channels": len(live_events),
        "events": list(live_events.values())
    }
    
    LIVE_OUTPUT_FILE = "live_epg.json"
    with open(LIVE_OUTPUT_FILE, 'w', encoding='utf-8') as f:
        json.dump(live_output, f, indent=2, ensure_ascii=False)
        
    logger.info(f"Live EPG salvato in {LIVE_OUTPUT_FILE} con {len(live_events)} canali in diretta.")

def main():
    load_wbd_images()
    load_tmdb_cache()
    
    last_full_update = None
    
    while True:
        try:
            now = datetime.now(ROME_TZ)
            
            # Condizioni per fare l'update completo dell'EPG:
            # 1. Non è mai stato fatto in questa sessione
            # 2. Il file non esiste
            # 3. È passata la mezzanotte e sono almeno le 00:05 (aggiornamento giornaliero)
            needs_full_update = False
            
            if last_full_update is None or not os.path.exists(OUTPUT_FILE):
                needs_full_update = True
            elif now.hour == 0 and now.minute >= 5 and last_full_update.day != now.day:
                needs_full_update = True
                
            if needs_full_update:
                update_full_epg()
                last_full_update = now
            
            # L'update LIVE si fa SEMPRE ad ogni loop (minuto)
            update_live_epg()
            
        except Exception as e:
            logger.error(f"Errore nel loop: {e}", exc_info=True)
        
        time.sleep(60)

if __name__ == "__main__":
    main()
