from __future__ import annotations

import json
from pathlib import Path
import sys
import tempfile
import threading
from urllib.request import Request, urlopen


ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from demo.server import build_server  # noqa: E402


def request_json(url: str, payload: dict[str, object] | None = None) -> dict[str, object]:
    body = None if payload is None else json.dumps(payload).encode("utf-8")
    request = Request(
        url,
        data=body,
        headers={"Content-Type": "application/json"} if body is not None else {},
        method="POST" if body is not None else "GET",
    )
    with urlopen(request, timeout=10) as response:
        assert response.status == 200
        value = json.loads(response.read().decode("utf-8"))
    assert value["ok"] is True
    return value["data"]


def main() -> None:
    with tempfile.TemporaryDirectory(prefix="agent-reliability-http-smoke-") as temp_dir:
        server = build_server(host="127.0.0.1", port=0, data_dir=Path(temp_dir))
        thread = threading.Thread(target=server.serve_forever, daemon=True)
        thread.start()
        host, port = server.server_address[:2]
        base_url = f"http://{host}:{port}"
        try:
            status = request_json(f"{base_url}/api/status")
            assert status["provider_mode"] == "sample"
            with urlopen(f"{base_url}/", timeout=10) as response:
                page = response.read().decode("utf-8")
                assert response.status == 200
                assert "AI가 문서를 읽고" in page

            analyzed = request_json(
                f"{base_url}/api/analyze",
                {
                    "document_text": status["sample_document"],
                    "fault_mode": "timeout_after_commit",
                },
            )
            assert analyzed["state"] == "APPROVAL_PENDING"
            assert analyzed["business_state"]["update_count"] == 0

            completed = request_json(
                f"{base_url}/api/approve",
                {"case_id": analyzed["case_id"]},
            )
            assert completed["state"] == "COMPLETED"
            assert completed["business_state"]["update_count"] == 1
            assert completed["duplicate_effect_count"] == 0
            assert completed["result_reuse_count"] >= 1

            replayed = request_json(
                f"{base_url}/api/replay",
                {"case_id": analyzed["case_id"]},
            )
            assert replayed["business_state"]["update_count"] == 1
            assert replayed["duplicate_effect_count"] == 0
            print("HTTP_SMOKE_TEST: PASS")
            print(
                json.dumps(
                    {
                        "provider_mode": status["provider_mode"],
                        "analyze_state": analyzed["state"],
                        "final_state": completed["state"],
                        "update_count_after_replay": replayed["business_state"]["update_count"],
                        "duplicate_effect_count": replayed["duplicate_effect_count"],
                    },
                    ensure_ascii=False,
                    indent=2,
                )
            )
        finally:
            server.shutdown()
            server.server_close()
            thread.join(timeout=5)


if __name__ == "__main__":
    main()
