#!/usr/bin/env python3
"""Minimal HTTP smoke-check for the active web surface."""
from __future__ import annotations

import argparse
from urllib.error import HTTPError, URLError
from urllib.parse import urljoin
from urllib.request import Request, urlopen


REQUIRED_PATHS = [
    "/web/index.html",
    "/web/game.html",
    "/web/map_review.html",
    "/web/cns_rect_review.html",
    "/web/battle_formula_calculator.html",
    "/web/battle_simulator.html",
    "/web/scene_event_vm_review.html",
    "/web/scene_event_runtime_evidence_handoff.html",
    "/out/scene_event_runtime_evidence_handoff.json",
    "/out/scene_event_vm_opcode_dictionary.json",
]

REQUIRED_MARKERS = {
    "/web/index.html": [
        "환세취호전 복원 관리 홈",
        "scene_event_runtime_evidence_handoff.html",
    ],
    "/web/scene_event_runtime_evidence_handoff.html": [
        "HWANSE_SCENE_EVENT_RUNTIME_EVIDENCE_HANDOFF_READY",
    ],
}


def fetch(url: str) -> tuple[int, bytes]:
    try:
        with urlopen(Request(url), timeout=8) as response:
            return response.status, response.read()
    except HTTPError as error:
        body = error.read()
        raise RuntimeError(f"{url} returned HTTP {error.code}: {body[:120]!r}") from error
    except URLError as error:
        raise RuntimeError(f"{url} is not reachable: {error.reason}") from error


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--base", default="http://127.0.0.1:8013")
    args = parser.parse_args()
    base = args.base.rstrip("/") + "/"

    for path in REQUIRED_PATHS:
        status, body = fetch(urljoin(base, path))
        if status != 200:
            raise RuntimeError(f"{path} returned status {status}")
        text = body.decode("utf-8", errors="replace")
        for marker in REQUIRED_MARKERS.get(path, []):
            if marker not in text:
                raise RuntimeError(f"{path} missing marker {marker!r}")
        print(f"ok {path} {len(body)} bytes")
    return 0


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