"""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

_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 clear_archive_playback() -> None:
    _HOME.clearProperty(ARCHIVE_PLAYBACK_FILE_PROP)


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 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()
    if not player.isPlayingVideo():
        return False

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

    if _is_plugin_archive_url(playing):
        return True
    if _is_archive_hls_url(playing):
        return True
    if _matches_registered_playback(playing):
        return True
    return False
