#!/usr/bin/env python3
"""Build a compact dialogue review summary from candidate browser smoke."""
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_FILE = "candidate_dialogue_progress_browser_smoke.json"


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


def build_summary(root: Path = ROOT) -> dict[str, Any]:
    out_dir = root / "out"
    path = out_dir / SOURCE_FILE
    payload = load_json(path)
    dialogue = {key: value for key, value in payload.items() if key != "snapshots"}
    dialogue["sourceFile"] = f"out/{SOURCE_FILE}"
    compact_size = len(json.dumps(dialogue, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
    return {
        "kind": "hwanse-dialogue-candidate-review-summary",
        "source": "tools/summarize_dialogue_candidate_review.py",
        "status": "ready",
        "sourceFile": f"out/{SOURCE_FILE}",
        "boundary": (
            "Compact browser dialogue review contract. It keeps the top-level dialogue smoke "
            "strings and small state objects used by web/dialogue_review.html, while dropping "
            "large raw snapshot payloads. Raw dialogue smoke remains a domain-summary and "
            "verifier input until those consumers are consolidated."
        ),
        "sourceSizeBytes": path.stat().st_size if path.exists() else 0,
        "compactSizeBytes": compact_size,
        "dialogue": dialogue,
    }


def html_page(summary: dict[str, Any]) -> str:
    dialogue = summary["dialogue"]
    rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(key)}</code></td>"
        f"<td>{html.escape(str(value))[:1200]}</td>"
        "</tr>"
        for key, value in dialogue.items()
    )
    return f"""<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <title>Dialogue 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>Dialogue Candidate Review Summary</h1>
  <p>{html.escape(summary['boundary'])}</p>
  <p><code>{html.escape(summary['sourceFile'])}</code>: {int(summary['sourceSizeBytes']):,} bytes raw, {int(summary['compactSizeBytes']):,} bytes compact.</p>
  <table>
    <thead><tr><th>field</th><th>value</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 / "dialogue_candidate_review_summary.json").write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    (out_dir / "dialogue_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()
