import os
import urllib.parse

SAFE_PUBLIC_HOSTS = {
    "httpbin.org",
    "postman-echo.com",
    "reqres.in",
}


def enforce_public_only(url: str) -> None:
    """Optional safety guardrail.

    If AI_SWARM_PUBLIC_ONLY=1, restrict runs to well-known public testing hosts.

    Use cases:
    - CI/demo mode (avoid accidentally hammering private/prod APIs)
    - contributor safety

    Default: OFF (no restrictions).
    """

    public_only = os.getenv("AI_SWARM_PUBLIC_ONLY", "0").lower() in {"1", "true", "yes"}
    if not public_only:
        return

    host = urllib.parse.urlparse(url).hostname
    if not host or host not in SAFE_PUBLIC_HOSTS:
        raise ValueError(
            f"AI_SWARM_PUBLIC_ONLY is enabled. Refusing host: {host!r}. "
            f"Allowed hosts: {sorted(SAFE_PUBLIC_HOSTS)}"
        )
