"""Read-only staging smoke. Never migrates, deploys, or calls production mutating APIs."""

from __future__ import annotations

import json
import urllib.error
import urllib.request
from datetime import UTC, datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "docs/audits/fixtures/13s_smoke.json"
STAGING = {
    "core_health": "https://stag1.piejet.com/health",
    "core_discovery_health": "https://stag1.piejet.com/api/discovery/health",
    "cloud_gateway": "https://stag-cloudgate.p2hs.com/",
    "dash": "https://devdash.p2hs.com/",
}
PRODUCTION = {
    "core_health": "https://beapipie.p2hs.com/health",
    "core_discovery_health": "https://beapipie.p2hs.com/api/discovery/health",
    "cloud_gateway": "https://cloudgate.p2hs.com/",
    "dash": "https://dashboard.p2hs.com/",
}
PRODUCTION_PREFIXES = (
    "https://beapipie.p2hs.com",
    "https://cloudgate.p2hs.com",
    "https://dashboard.p2hs.com",
)


def fetch(url: str) -> dict:
    request = urllib.request.Request(url, method="GET", headers={"User-Agent": "p2hs-13s-smoke"})
    try:
        with urllib.request.urlopen(request, timeout=12) as response:
            body = response.read(2048)
            return {
                "url": url,
                "reached": True,
                "healthy": 200 <= response.status < 400,
                "status": response.status,
                "final_url": response.geturl(),
                "bytes": len(body),
            }
    except urllib.error.HTTPError as exc:
        return {
            "url": url,
            "reached": True,
            "healthy": False,
            "status": exc.code,
            "final_url": exc.geturl() or url,
            "error": "HTTPError",
        }
    except Exception as exc:  # noqa: BLE001 — smoke records the failure class only
        return {
            "url": url,
            "reached": False,
            "healthy": False,
            "status": None,
            "final_url": url,
            "error": type(exc).__name__,
        }


def main() -> int:
    if set(STAGING.values()) & set(PRODUCTION.values()):
        raise SystemExit("staging URLs must not equal production URLs")
    staging = {name: fetch(url) for name, url in STAGING.items()}
    production = {name: fetch(url) for name, url in PRODUCTION.items()}
    crossed = [
        name
        for name, row in staging.items()
        if any(
            str(row.get("final_url", "")).startswith(prefix)
            for prefix in PRODUCTION_PREFIXES
        )
    ]
    core_ok = bool(
        staging["core_health"].get("healthy")
        or staging["core_discovery_health"].get("healthy")
    )
    cloud_ok = bool(staging["cloud_gateway"].get("healthy"))
    dash_ok = bool(staging["dash"].get("healthy"))
    payload = {
        "generated_at": datetime.now(UTC).isoformat(),
        "mutating_calls": 0,
        "staging": staging,
        "production_reachability_control": production,
        "staging_redirected_to_production": sorted(set(crossed)),
        "core_staging_healthy": core_ok,
        "cloud_staging_healthy": cloud_ok,
        "dash_staging_healthy": dash_ok,
        "wiring_ok": core_ok and cloud_ok and dash_ok and not crossed,
    }
    OUT.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(payload, indent=2))
    return 0 if payload["wiring_ok"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
