"""Trakt/session hooky, Trakt↔menu rozcestí a akce nad seriály (validace streamů)."""

import importlib

import xbmc
import xbmcgui
import xbmcplugin

from resources.lib.core.router_state import (
    ADDON_NAME,
    _addon,
    _handle,
    _profile,
    get_url,
    log,
)

_router_session_hooks_done = False


def _ensure_router_session_hooks():
    """Jednorázově za běh procesu pluginu: Trakt refresh, nové epizody (dříve při importu)."""
    global _router_session_hooks_done
    if _router_session_hooks_done:
        return
    _router_session_hooks_done = True
    win = xbmcgui.Window(10000)
    if win.getProperty('mm_trakt_auto_refresh_done') != '1':
        log.info("Spouštím auto-refresh Trakt tokenu (první start v relaci)")
        try:
            from resources.lib.trakt.trakt_module import maybe_refresh_on_start

            maybe_refresh_on_start(threshold_hours=12)
        except Exception as e:
            log.error(f"TraktAutoRefresh selhalo: {e}")
        win.setProperty('mm_trakt_auto_refresh_done', '1')

    if win.getProperty('mm_new_eps_notified') != '1':
        log.info("Spouštím kontrolu nově vydaných epizod z Trakt kalendáře")
        try:
            from resources.lib.trakt.trakt_module import (
                check_new_episodes_notifications,
            )

            check_new_episodes_notifications(_addon)
        except Exception as e:
            log.error(f"check_new_episodes_notifications selhalo: {e}")
        win.setProperty('mm_new_eps_notified', '1')


def _update_progress_view():
    try:
        url = get_url(
            action='trakt_shows_progress',
            page=1,
            limit=20,
            mode='cache',
            only_incomplete='true',
        )
        xbmc.executebuiltin(f'Container.Update({url})')
    except Exception as e:
        log.error(f"update progress view failed: {e}")
        xbmc.executebuiltin('Container.Refresh')


def _resolve_trakt_id_and_call(action_type, p):
    media_type = (p.get('media_type') or 'movies').strip()
    ident = (p.get('id') or '').strip()
    title = p.get('title', '')

    try:
        page = int(p.get('page', 1))
    except Exception:
        page = 1
    try:
        limit = int(p.get('limit', 30))
    except Exception:
        limit = 20

    if ident.isdigit():
        try:
            from resources.lib.trakt.trakt_service import TraktAPI

            api_client = TraktAPI()
            search_type = 'movie' if media_type == 'movies' else 'show'
            search = api_client.get(
                f"search/tmdb/{ident}",
                params={'type': search_type},
                auth=False,
                cache_ttl=0,
            )
            if search and isinstance(search, list):
                obj = (search[0].get(search_type) or {})
                ids = obj.get('ids') or {}
                ident = ids.get('slug') or str(ids.get('trakt') or '')
        except Exception as e:
            log.warning(f"TMDb→Trakt lookup failed: {e}")

    if not ident:
        xbmcgui.Dialog().notification(
            'Trakt',
            'Nelze načíst Trakt ID pro tento titul.',
            xbmcgui.NOTIFICATION_WARNING,
        )
        xbmcplugin.endOfDirectory(_handle, succeeded=False)
        return
    elif p['action'] == 'csfd_top':
        from resources.lib.csfd_toplist.router import handle_csfd_top

        handle_csfd_top(p)

    try:
        from resources.lib.trakt.trakt_module import TraktMenu

        menu = TraktMenu(_handle, _addon)
        if action_type == 'people':
            menu.show_people(media_type, ident, title)
        elif action_type == 'related':
            menu.show_related(media_type, ident, page, limit)
    except Exception as e:
        log.error(f"resolver call failed: {e}")
        xbmcgui.Dialog().notification(
            _addon.getAddonInfo('name'),
            "Chyba akce.",
            xbmcgui.NOTIFICATION_ERROR,
            3000,
        )
        xbmcplugin.endOfDirectory(_handle, succeeded=False)


def _validate_streams_action(series_name):
    from resources.lib.core.router_webshare import api, revalidate
    from resources.lib.series import series_manager as sm_mod

    importlib.reload(sm_mod)

    sm = sm_mod.SeriesManager(_addon, _profile)
    token = revalidate()
    if not token:
        xbmcgui.Dialog().notification(
            ADDON_NAME,
            "Nejste přihlášeni k Webshare.",
            xbmcgui.NOTIFICATION_WARNING,
        )
        return
    results = sm.validate_all_streams(series_name, token, api)
    xbmcgui.Dialog().ok(
        ADDON_NAME,
        f"Validace dokončena. Nalezeno "
        f"{results['invalid']} neplatných z {results['total']}.",
    )


def _rescan_invalid_action(series_name):
    from resources.lib.series import series_manager as sm_mod
    from resources.lib.series import search_engine, update_engine

    importlib.reload(sm_mod)
    importlib.reload(search_engine)
    importlib.reload(update_engine)

    sm = sm_mod.SeriesManager(_addon, _profile)
    data = sm.load_series_data(series_name)
    if not data:
        xbmcgui.Dialog().notification(
            ADDON_NAME,
            "Data seriálu nenalezena.",
            xbmcgui.NOTIFICATION_ERROR,
        )
        return

    dp = xbmcgui.DialogProgress()
    dp.create("Přeskenování neplatných", "Inicializace...")
    total_seasons = len(data.get('seasons', {}))
    s_done = 0
    updated_count = 0

    for s_key, s_data in (data.get('seasons', {}) or {}).items():
        if dp.iscanceled():
            break
        dp.update(
            int(s_done * 100 / total_seasons),
            f"Sezóna {s_key}...",
        )
        for e_key, e_data in (s_data or {}).items():
            if dp.iscanceled():
                break
            if not e_key.isdigit():
                continue
            valid_streams = [
                st
                for st in (e_data.get('streams') or [])
                if st.get('valid') is not False
            ]
            if not valid_streams:
                log.info(f"Rescan S{s_key}E{e_key}")
                ep_title = e_data.get('name') or e_data.get('title')
                if ep_title:
                    new_streams = update_engine.find_and_sort_streams(
                        series_name, s_key, e_key, ep_title
                    )
                    if new_streams:
                        sm.update_episode_streams(
                            series_name, s_key, e_key, new_streams
                        )
                        updated_count += 1
                        xbmc.sleep(200)
        s_done += 1
    dp.close()
    xbmcgui.Dialog().notification(
        ADDON_NAME,
        f"Přeskenování dokončeno, aktualizováno {updated_count} epizod.",
        xbmcgui.NOTIFICATION_INFO,
        3000,
    )


def _trakt_auth_with_status():
    log.debug('=== START Trakt autorizace z nastavení ===')
    try:
        from resources.lib.trakt.trakt_service import (
            TraktAPI as TraktAuthAPI,
            update_trakt_status_setting,
        )

        TraktAuthAPI().authorize_trakt()
        update_trakt_status_setting()
        xbmcgui.Dialog().notification(
            'Trakt',
            'Autorizace dokončena (pokud byla potvrzena na webu).',
            xbmcgui.NOTIFICATION_INFO,
            2500,
        )
    except ValueError as e:
        log.error(f'TRAKT INIT ERROR: Chybí ID/Secret: {e}')
        xbmcgui.Dialog().notification(
            'Trakt',
            'Chybí Client Secret v nastavení.',
            xbmcgui.NOTIFICATION_ERROR,
            3000,
        )
    except ImportError as e:
        log.critical(
            f'TRAKT CRITICAL ERROR: Nelze importovat Trakt modul: {e}'
        )
        xbmcgui.Dialog().notification(
            'Chyba Trakt',
            'Nelze importovat Trakt modul. Zkontrolujte soubor.',
            xbmcgui.NOTIFICATION_ERROR,
            3000,
        )
    except Exception as e:
        log.critical(f'TRAKT UNEXPECTED ERROR: {e}')
        xbmcgui.Dialog().notification(
            'Chyba Trakt',
            'Nečekaná chyba v autorizaci. Viz log.',
            xbmcgui.NOTIFICATION_ERROR,
            3000,
        )


def _trakt_refresh_status():
    try:
        from resources.lib.trakt.trakt_service import update_trakt_status_setting

        update_trakt_status_setting()
        xbmcgui.Dialog().notification(
            'Trakt',
            'Stav aktualizován.',
            xbmcgui.NOTIFICATION_INFO,
            1500,
        )
    except Exception as e:
        log.error(f'trakt_refresh_status error: {e}')
        xbmcgui.Dialog().notification(
            'Trakt',
            'Chyba aktualizace stavu.',
            xbmcgui.NOTIFICATION_ERROR,
            3000,
        )
