#!/usr/bin/env python3
"""Build a compact completion review summary from candidate browser smokes."""
from __future__ import annotations

import argparse
import html
import json
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "out"

SOURCE_FILES = {
    "route": "candidate_route_progress_browser_smoke.json",
    "deep": "candidate_deep_route_browser_smoke.json",
}

ROUTE_FIELDS = [
    "status",
    "routeCompletionNotice",
    "routeClearGateTitleRestore",
    "titleRouteCompletionGate",
    "titleRouteClearGate",
]

DEEP_FIELDS = [
    "status",
    "target",
    "hopCount",
    "path",
    "actionCount",
    "candidateEntryCount",
    "final",
    "titleContinue",
    "fieldEncounter",
    "completionTitleContinue",
    "routeClearTitleContinue",
    "expectedCandidateCount",
    "activationCount",
    "candidateEdges",
    "candidateEdgeCounts",
    "visitedMaps",
    "completionNotice",
    "routeClearGate",
]


def load_json(path: Path) -> dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}


def compact(payload: dict[str, Any], fields: list[str], source_file: str) -> dict[str, Any]:
    row = {field: payload.get(field) for field in fields if field in payload}
    row["sourceFile"] = source_file
    return row


def source_info(path: Path, row: dict[str, Any]) -> dict[str, Any]:
    return {
        "sourceFile": f"out/{path.name}",
        "sourceSizeBytes": path.stat().st_size if path.exists() else 0,
        "compactSizeBytes": len(json.dumps(row, ensure_ascii=False, separators=(",", ":")).encode("utf-8")),
        "status": row.get("status", "missing"),
    }


def build_summary(root: Path = ROOT) -> dict[str, Any]:
    out_dir = root / "out"
    route_path = out_dir / SOURCE_FILES["route"]
    deep_path = out_dir / SOURCE_FILES["deep"]
    route = compact(load_json(route_path), ROUTE_FIELDS, f"out/{route_path.name}")
    deep = compact(load_json(deep_path), DEEP_FIELDS, f"out/{deep_path.name}")
    return {
        "kind": "hwanse-completion-candidate-review-summary",
        "source": "tools/summarize_completion_candidate_review.py",
        "status": "ready",
        "sourceFiles": SOURCE_FILES,
        "boundary": (
            "Compact browser completion review contract. It keeps only fields used by "
            "web/completion_review.html and tools/summarize_completion_audit.py; raw "
            "route/deep browser smoke payloads remain verifier outputs until their "
            "remaining active consumers are replaced."
        ),
        "sources": {
            "route": source_info(route_path, route),
            "deep": source_info(deep_path, deep),
        },
        "route": route,
        "deep": deep,
    }


def html_page(summary: dict[str, Any]) -> str:
    rows = "\n".join(
        "<tr>"
        f"<td id=\"{html.escape(key)}\"><code>{html.escape(key)}</code></td>"
        f"<td>{html.escape(str(info.get('status', '-')))}</td>"
        f"<td><code>{html.escape(str(info.get('sourceFile', '-')))}</code></td>"
        f"<td>{int(info.get('sourceSizeBytes') or 0):,}</td>"
        f"<td>{int(info.get('compactSizeBytes') or 0):,}</td>"
        "</tr>"
        for key, info in summary["sources"].items()
    )
    return f"""<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <title>Completion Candidate Review Summary</title>
  <style>
    body {{ margin: 24px; color: #202124; font-family: system-ui, sans-serif; line-height: 1.5; }}
    table {{ width: 100%; border-collapse: collapse; margin: 14px 0 28px; }}
    th, td {{ border: 1px solid #d7dce2; padding: 6px 8px; text-align: left; vertical-align: top; }}
    th {{ background: #f4f6f8; }}
    code {{ background: #f4f6f8; padding: 1px 4px; }}
  </style>
</head>
<body>
  <h1>Completion Candidate Review Summary</h1>
  <p>{html.escape(summary['boundary'])}</p>
  <table>
    <thead><tr><th>scope</th><th>status</th><th>raw source</th><th>raw bytes</th><th>compact bytes</th></tr></thead>
    <tbody>{rows}</tbody>
  </table>
</body>
</html>
"""


def write_outputs(summary: dict[str, Any], out_dir: Path = OUT) -> None:
    out_dir.mkdir(parents=True, exist_ok=True)
    (out_dir / "completion_candidate_review_summary.json").write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    (out_dir / "completion_candidate_review_summary.html").write_text(html_page(summary), encoding="utf-8")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, default=ROOT)
    args = parser.parse_args()
    root = args.root.resolve()
    write_outputs(build_summary(root), root / "out")


if __name__ == "__main__":
    main()
