"""EPG cesty, lazy TVProgram a obnova dat."""

import os
from datetime import datetime, timedelta

import xbmcgui

from resources.lib.core.router_state import (
    ADDON_ID,
    ADDON_NAME,
    _addon,
    _handle,
    _profile,
    _url,
    log,
)
try:
    from xbmc import translatePath
except ImportError:
    from xbmcvfs import translatePath

EPG_DIR = os.path.join(_profile, "epg")
EPG_JSON = os.path.join(EPG_DIR, "epg_all.json")


def _ensure_epg_dir():
    if not os.path.isdir(EPG_DIR):
        os.makedirs(EPG_DIR, exist_ok=True)

_tv_program = None


def _get_tv_program():
    global _tv_program
    if _tv_program is None:
        _ensure_epg_dir()
        from resources.lib.epg.tvprogram import TVProgram

        _tv_program = TVProgram(
            handle=_handle,
            base_url=_url,
            addon_id=ADDON_ID,
            addon_path=translatePath(_addon.getAddonInfo("path")),
            addon_data_path=_profile,
            json_file=EPG_JSON,
            route_prefix="tvprog",
            use_colors=True,
        )
    return _tv_program


def ensure_epg_fresh():
    _ensure_epg_dir()
    from resources.lib.epg.epg_updater import ensure_default_channels, update_epg

    try:
        ensure_default_channels(EPG_DIR)
    except Exception as e:
        log.error(f"CHYBA při přípravě kanálů: {e}")

    need_update = False
    if not os.path.exists(EPG_JSON):
        need_update = True
    else:
        try:
            mtime = datetime.fromtimestamp(os.path.getmtime(EPG_JSON))
            now = datetime.now()
            if mtime < (now - timedelta(hours=72)):
                need_update = True
        except Exception:
            need_update = True

    if not need_update:
        return

    try:
        update_epg(EPG_DIR, days_forward=3)
    except Exception as e:
        log.error(f"CHYBA při aktualizaci EPG: {e}")
        xbmcgui.Dialog().ok(ADDON_NAME, f"Chyba při aktualizaci EPG: {e}")
