"""Optional helpers importable from web-act user scripts."""
from __future__ import annotations

import json
import os
from urllib.parse import urlparse


def allowed_hosts() -> frozenset[str]:
    raw = os.environ.get("MUGI_WEB_ACT_ALLOWED_HOSTS", "").strip()
    if not raw:
        return frozenset()
    try:
        parsed = json.loads(raw)
        if isinstance(parsed, list):
            return frozenset(str(h).strip().lower() for h in parsed if str(h).strip())
    except json.JSONDecodeError:
        pass
    return frozenset(h.strip().lower() for h in raw.split(",") if h.strip())


def _host_allowed(url: str) -> bool:
    hosts = allowed_hosts()
    if not hosts:
        return True
    host = (urlparse(url).hostname or "").strip().lower()
    if not host:
        return False
    return host in hosts or any(host.endswith(f".{h}") for h in hosts if h)


def safe_goto(page, url: str, **kwargs):
    """Navigate only when *url* host is allowlisted (no-op restriction when list empty)."""
    if not _host_allowed(url):
        allowed = sorted(allowed_hosts())
        raise PermissionError(
            f"Host not in web-act allowlist: {urlparse(url).hostname!r}. "
            f"Allowed: {allowed or '(none configured)'}"
        )
    return page.goto(url, **kwargs)
