import os
from typing import Dict, Optional

from .runtime import kyb_headers


_INSTALLED_REQUESTS = False
_INSTALLED_HTTPX = False


def _env(name: str, default: str = "") -> str:
    v = os.getenv(name)
    return v if v is not None else default


def _truthy(val: str, default: bool = True) -> bool:
    if val is None or str(val).strip() == "":
        return default
    return str(val).strip().lower() in {"1", "true", "yes", "on"}


def _build_headers(existing: Optional[Dict[str, str]] = None) -> Dict[str, str]:
    return kyb_headers(existing)


def _enforce_egress() -> None:
    if not _truthy(_env("KYB_ENFORCE_EGRESS", "0"), default=False):
        return
    if _env("HTTP_PROXY") or _env("HTTPS_PROXY"):
        return
    raise RuntimeError("KYB_ENFORCE_EGRESS=1 requires HTTP_PROXY/HTTPS_PROXY")


def install_requests_patch() -> None:
    global _INSTALLED_REQUESTS
    if _INSTALLED_REQUESTS:
        return
    _INSTALLED_REQUESTS = True

    try:
        import requests  # type: ignore
    except Exception:
        return

    original = requests.sessions.Session.request

    def patched(self, method, url, **kwargs):
        _enforce_egress()
        headers = kwargs.get("headers") or {}
        kwargs["headers"] = _build_headers(headers)
        return original(self, method, url, **kwargs)

    requests.sessions.Session.request = patched  # type: ignore[attr-defined]


def install_httpx_patch() -> None:
    global _INSTALLED_HTTPX
    if _INSTALLED_HTTPX:
        return
    _INSTALLED_HTTPX = True

    try:
        import httpx  # type: ignore
    except Exception:
        return

    original = httpx.Client.request

    def patched(self, method, url, **kwargs):
        _enforce_egress()
        headers = kwargs.get("headers") or {}
        kwargs["headers"] = _build_headers(headers)
        return original(self, method, url, **kwargs)

    httpx.Client.request = patched  # type: ignore[attr-defined]
