# -*- coding: utf-8 -*-
"""
Testovací / diagnostický modul: CZ detekce přes HTTP Range (Android kontextové menu).

Jádro sondy je v resources.lib.series.http_range_probe — tento soubor jen získá URL,
spustí sondu a zobrazí textviewer.
"""

import xbmc
import xbmcgui
import xbmcplugin

from resources.lib.utils.log_utils import get_logger
from resources.lib.series.subs_probe import _get_stream_url
from resources.lib.series.http_range_probe import (
    run_http_range_probe,
    format_probe_dialog_lines,
)

log = get_logger()


def run_android_range_probe_test(params, addon, handle, api, revalidate, popinfo):
    """Spustí izolovaný test CZ detekce přes HTTP Range requesty."""
    ident = params.get("ident")
    name = params.get("name") or "Stream"

    if not ident:
        popinfo("TEST Android probe: chybí ident streamu", icon=xbmcgui.NOTIFICATION_WARNING)
        xbmcplugin.endOfDirectory(handle, succeeded=False)
        return

    progress = xbmcgui.DialogProgress()
    progress.create("TEST Android CZ probe", f"Získávám link pro:\n{name}")

    session = None
    try:
        log.info(f"TEST probe start ident={ident} name={name}")

        token = revalidate()
        duuid = addon.getSetting("duuid")
        url = _get_stream_url(api, token, ident, duuid)
        if not url:
            popinfo("TEST Android probe: file_link nenalezen", icon=xbmcgui.NOTIFICATION_WARNING)
            log.warning("TEST probe aborted: file_link missing")
            xbmcplugin.endOfDirectory(handle, succeeded=False)
            return

        log.info(f"TEST probe resolved stream url={str(url).split('?', 1)[0]}")

        try:
            import requests
            session = requests.Session()
            log.info("TEST probe using requests.Session() for keep-alive")
        except Exception as ex:
            log.warning(f"TEST probe failed to create Session, fallback to requests.get: {ex}")

        def _cb(pct, msg):
            try:
                progress.update(pct, msg)
            except Exception:
                pass

        probe_result = run_http_range_probe(url, session=session, progress_callback=_cb)

        lines = format_probe_dialog_lines(name, probe_result)
        xbmcgui.Dialog().textviewer("TEST Android CZ probe", "\n".join(lines))
        xbmcplugin.endOfDirectory(handle, succeeded=False)
    except Exception as ex:
        log.error(f"TEST probe fatal error: {ex}", exc_info=True)
        popinfo(f"TEST Android probe selhal: {ex}", icon=xbmcgui.NOTIFICATION_ERROR)
        xbmcplugin.endOfDirectory(handle, succeeded=False)
    finally:
        if session is not None:
            try:
                session.close()
            except Exception:
                pass
        try:
            progress.close()
        except Exception:
            pass
