"""Detect Antik archive playback (Stations / Genres / History) vs other streams."""
from __future__ import annotations

import urllib.parse

import xbmc

from xbmcgui import Window

from .constants import (
    ADDON_ID,
    ARCHIVE_PLAYBACK_FILE_PROP,
    ARCHIVE_SESSION_PROP,
)

_HOME = Window(10000)
_PLUGIN_PREFIX = f"plugin://{ADDON_ID}/".lower()


def _strip_url_extras(url: str) -> str:
    text = (url or "").strip()
    pipe = text.find("|")
    if pipe >= 0:
        text = text[:pipe]
    return text


def _normalize_url(url: str) -> str:
    return _strip_url_extras(url).lower()


def set_archive_playback_file(url: str) -> None:
    clean = _strip_url_extras(url)
    if clean:
        _HOME.setProperty(ARCHIVE_PLAYBACK_FILE_PROP, clean)


def begin_archive_session(url: str = "") -> None:
    """Mark active archive playback until explicit clear (resolve/play)."""
    _HOME.setProperty(ARCHIVE_SESSION_PROP, "1")
    if url:
        set_archive_playback_file(url)


def clear_archive_playback() -> None:
    _HOME.clearProperty(ARCHIVE_PLAYBACK_FILE_PROP)
    _HOME.clearProperty(ARCHIVE_SESSION_PROP)


def archive_session_active() -> bool:
    return _HOME.getProperty(ARCHIVE_SESSION_PROP) == "1"


def _is_plugin_archive_url(url: str) -> bool:
    normalized = _normalize_url(url)
    if not normalized.startswith(_PLUGIN_PREFIX):
        return False
    query = normalized.split("?", 1)[-1]
    params = urllib.parse.parse_qs(query, keep_blank_values=True)
    action = (params.get("action") or [""])[0].lower()
    return action == "play"


def _is_archive_hls_url(url: str) -> bool:
    normalized = _normalize_url(url)
    return "/stream/archive/" in normalized and "playlist.m3u8" in normalized


def _matches_registered_playback(playing: str) -> bool:
    stored = _strip_url_extras(_HOME.getProperty(ARCHIVE_PLAYBACK_FILE_PROP) or "")
    if not stored:
        return False
    playing_clean = _strip_url_extras(playing)
    if playing_clean == stored:
        return True
    stored_base = stored.split("?", 1)[0].lower()
    playing_base = playing_clean.split("?", 1)[0].lower()
    return bool(stored_base) and playing_base == stored_base


def _url_is_archive_playback(url: str) -> bool:
    if not url:
        return False
    if _is_plugin_archive_url(url):
        return True
    if _is_archive_hls_url(url):
        return True
    if _matches_registered_playback(url):
        return True
    return False


def is_antik_archive_playback(player: xbmc.Player | None = None) -> bool:
    """True only for archive items played via this addon (not VOD, live, or other add-ons)."""
    if player is None:
        player = xbmc.Player()

    playing = player.getPlayingFile() or ""
    if playing:
        return _url_is_archive_playback(playing)

    # Resolve/startup before Kodi exposes the stream URL — trust session marker.
    return archive_session_active()
