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


def resolve(url: str) -> Optional[str]:
    if not url:
        return None
    try:
        import resolveurl  # type: ignore
    except Exception:
        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():
                return None
            resolver = getattr(hmf, "resolve", None)
            if callable(resolver):
                result = resolver()
                return str(result) if result else None
    except Exception:
        pass

    try:
        resolve_fn = getattr(resolveurl, "resolve", None)
        if callable(resolve_fn):
            result = resolve_fn(url)
            return str(result) if result else None
    except Exception:
        return None

    return None

