"""Optionales ResolveURL-Backend für das Kodi-Addon.

Wenn `script.module.resolveurl` installiert ist, kann damit eine Hoster-URL
zu einer abspielbaren Media-URL (inkl. evtl. Header-Suffix) aufgelöst werden.
"""

from __future__ import annotations

from typing import Optional

_LAST_RESOLVE_ERROR = ""


def get_last_error() -> str:
    return str(_LAST_RESOLVE_ERROR or "")


def resolve(url: str) -> Optional[str]:
    global _LAST_RESOLVE_ERROR
    _LAST_RESOLVE_ERROR = ""
    if not url:
        return None
    try:
        import resolveurl  # type: ignore
    except Exception:
        _LAST_RESOLVE_ERROR = "resolveurl missing"
        return None

    try:
        hosted = getattr(resolveurl, "HostedMediaFile", None)
        if callable(hosted):
            hmf = hosted(url)
            valid = getattr(hmf, "valid_url", None)
            if callable(valid) and not valid():
                _LAST_RESOLVE_ERROR = "invalid url"
                return None
            resolver = getattr(hmf, "resolve", None)
            if callable(resolver):
                result = resolver()
                if result:
                    return str(result)
                _LAST_RESOLVE_ERROR = "unresolved"
                return None
    except Exception as exc:
        _LAST_RESOLVE_ERROR = str(exc or "")
        pass

    try:
        resolve_fn = getattr(resolveurl, "resolve", None)
        if callable(resolve_fn):
            result = resolve_fn(url)
            if result:
                return str(result)
            _LAST_RESOLVE_ERROR = "unresolved"
            return None
    except Exception as exc:
        _LAST_RESOLVE_ERROR = str(exc or "")
        return None

    return None
