# -*- coding: utf-8 -*-
import os
import json
import time
import threading
import requests
from datetime import datetime, timedelta
from resources.lib.utils.log_utils import get_logger

try:
    import xbmc
    import xbmcgui
except ImportError:
    xbmc = None
    xbmcgui = None

log = get_logger()

# ---- Konfigurace ----
API_URL = "https://api-cz.webtv.tv/epg/channel"
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"
HEADERS = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "cs",
    "appversion": "6.6.0",
    "content-type": "application/json",
    "referer": "https://webtv.tv/",
    "user-agent": USER_AGENT,
}

CHANNEL_NAME_MAP = {
    "smichov": "Nova Fun",
    "tv_fanfa": "Nova Cinema",
    "telka": "Nova Krimi",
    "prima_news": "CNN Prima News",
}

DEFAULT_CHANNELS = [
    "nova", "prima", "prima_cool", "prima_krimi", "prima_max", "nova_cinema",
    "hbo", "hbo_2", "hbo_3", "cinemax", "ct_1_sm", "seznam_tv",
    "prima_comedy_central", "warner", "joj_cinema", "joj_family", "cinemax_2",
    "filmbox_extra_hd", "filmbox_premium", "filmbox_family", "filmbox_plus",
    "amc", "film_plus", "cs_film", "axn", "axn_white", "axn_black",
]

def _ensure_dir(path_dir: str):
    if not os.path.isdir(path_dir):
        os.makedirs(path_dir, exist_ok=True)

def _atomic_write_json(target_path: str, data_obj):
    tmp_path = target_path + ".tmp"
    with open(tmp_path, "w", encoding="utf-8") as f:
        json.dump(data_obj, f, ensure_ascii=False, indent=2)
    if os.path.exists(target_path):
        os.remove(target_path)
    os.rename(tmp_path, target_path)

def ensure_default_channels(epg_dir: str) -> list:
    _ensure_dir(epg_dir)
    channels_path = os.path.join(epg_dir, "kanaly_id.json")
    if not os.path.exists(channels_path):
        _atomic_write_json(channels_path, DEFAULT_CHANNELS)
        return list(DEFAULT_CHANNELS)
    try:
        with open(channels_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        return [str(ch).strip() for ch in data if str(ch).strip()] if isinstance(data, list) else list(DEFAULT_CHANNELS)
    except Exception:
        return list(DEFAULT_CHANNELS)

def update_epg(epg_dir: str, days_forward: int = 5, pause_seconds: float = 0.3) -> str:
    """Aktualizuje EPG s funkčním Progress Barem (threading)."""
    _ensure_dir(epg_dir)
    channels = ensure_default_channels(epg_dir)
    out_path = os.path.join(epg_dir, "epg_all.json")
    
    total_steps = len(channels) * (days_forward + 1)
    state = {"percent": 0, "msg": "Inicializace...", "done": False, "error": None, "stop": False}

    def worker():
        try:
            sess = requests.Session()
            output = []
            today = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
            step = 0
            for ch in channels:
                if state["stop"]: return
                chan_data = []
                for off in range(days_forward + 1):
                    if state["stop"]: return
                    date_str = (today + timedelta(days=off)).strftime("%Y-%m-%dT00:00:00.000Z")
                    step += 1
                    state["percent"] = int(step * 100 / total_steps)
                    state["msg"] = f"Kanál: {CHANNEL_NAME_MAP.get(ch, ch)} ({step}/{total_steps})"
                    
                    try:
                        resp = sess.post(API_URL, json={"channel_id": ch, "date": date_str, "limit": "2000", "ofset": "0"}, 
                                         headers=HEADERS, timeout=10)
                        data = resp.json()
                        if isinstance(data, dict) and isinstance(data.get("content"), list):
                            chan_data.extend(data["content"])
                    except Exception as e:
                        log.warning(f"Chyba {ch} dne {off}: {e}")
                    
                    if pause_seconds: time.sleep(pause_seconds)
                
                output.append(CHANNEL_NAME_MAP.get(ch, ch))
                output.append(chan_data)
            
            _atomic_write_json(out_path, output)
            state["done"] = True
        except Exception as e:
            state["error"] = str(e)
            log.error(f"Kritická chyba workeru: {e}")

    thread = threading.Thread(target=worker)
    thread.daemon = True
    thread.start()

    dp = xbmcgui.DialogProgress()
    dp.create("TV Program", "Aktualizuji EPG, vyčkejte prosím...")

    while thread.is_alive() and not state["done"] and not state["error"]:
        if dp.iscanceled():
            state["stop"] = True
            break
        dp.update(state["percent"], state["msg"])
        xbmc.sleep(200)

    dp.close()
    if state["error"]:
        xbmcgui.Dialog().ok("TV Program", f"Chyba při aktualizaci: {state['error']}")
    elif state["done"]:
        xbmcgui.Dialog().notification("TV Program", "EPG úspěšně aktualizováno.", xbmcgui.NOTIFICATION_INFO, 3000)
    
    return out_path
