"""Headless HTTP smoke: serve recoil/ and confirm atlas.html + its RELATIVE render-
JSON fetch both resolve over HTTP. file:// fetches fail and the page's
`../architecture/topology/generated/atlas.render.json` only resolves under the
recoil/ HTTP root — this gate proves that path is right. Runtime DOM hover/click is
verified in the post-build human-verify step (no headless browser in the build env)."""
from __future__ import annotations

import json
import threading
from functools import partial
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
from urllib.request import urlopen

_MONO = Path(__file__).resolve().parents[4]
_ROOT = _MONO / "recoil"   # server root: makes /docs/atlas.html + /architecture/... resolve


def _serve() -> HTTPServer:
    handler = partial(SimpleHTTPRequestHandler, directory=str(_ROOT))
    httpd = HTTPServer(("127.0.0.1", 0), handler)  # ephemeral port
    threading.Thread(target=httpd.serve_forever, daemon=True).start()
    return httpd


def test_viewer_and_render_json_serve_over_http():
    try:
        httpd = _serve()
    except (PermissionError, OSError) as e:
        import pytest
        pytest.skip(
            f"socket bind not permitted in this sandbox ({e}); the http smoke runs in "
            "unsandboxed envs and is backed by the static wiring test + the blocking "
            "human browser-verify (see BUILD_SPEC Post-build acceptance)."
        )
    try:
        port = httpd.server_address[1]
        base = f"http://127.0.0.1:{port}"
        with urlopen(f"{base}/docs/atlas.html", timeout=10) as r:
            assert r.status == 200, "atlas.html did not serve 200"
        # the page's relative fetch target, resolved against the recoil/ root:
        with urlopen(f"{base}/architecture/topology/generated/atlas.render.json", timeout=10) as r:
            assert r.status == 200, "render JSON not reachable at the page's relative path"
            g = json.loads(r.read())
        assert g["meta"]["node_count"] == len(g["nodes"])
        humans = [n["id"] for n in g["nodes"] if n["is_human_review"]]
        subs = sorted(n["id"] for n in g["nodes"] if n["is_substrate"])
        assert len(humans) == 6, f"expected 6 human gates, got {humans}"
        assert subs == ["eval_panel", "modality_eval", "strategy_score_bridge"]
    finally:
        httpd.shutdown()
