#!/usr/bin/env python3
"""Summarize scene event dispatch references and their condition blocks."""
from __future__ import annotations

import argparse
import json
from pathlib import Path


def summarize(events: list[dict]) -> str:
    lines = [
        "# Scene Dispatch Reference Summary",
        "",
        "| map | scene | kind | dispatch | refs | condition blocks | condition linked | record |",
        "| --- | --- | ---: | --- | ---: | --- | --- | --- |",
    ]
    for event in events:
        refs = event.get("eventDispatchRefs", [])
        condition_blocks = []
        linked_strings = []
        seen_links = set()
        for ref in refs:
            condition = ref.get("conditionVa")
            if not condition:
                continue
            first = ref.get("conditionFirstDwords", [])
            head = first[0]["hex"] if first else "?"
            condition_blocks.append(f"0x{condition:08x}:{head}")
            for linked in ref.get("conditionLinkedStrings", []):
                if linked in seen_links:
                    continue
                seen_links.add(linked)
                linked_strings.append(linked)
        lines.append(
            "| {map} | {scene} | {kind} | `{dispatch}` | {refs} | {conditions} | {linked} | `{record}` |".format(
                map=event["map"],
                scene=event["sceneIdHex"],
                kind=event["eventKind"],
                dispatch=f"0x{event.get('eventDispatchVa', event['recordVa'] + 12):08x}",
                refs=len(refs),
                conditions=", ".join(condition_blocks[:12]) or "-",
                linked=", ".join(linked_strings[:16]) or "-",
                record=f"0x{event['recordVa']:08x}",
            )
        )
    lines.append("")
    return "\n".join(lines)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--events", type=Path, default=Path("out/scene_events.json"))
    parser.add_argument("--out", type=Path, default=Path("out/scene_dispatch_summary.md"))
    args = parser.parse_args()

    events = json.loads(args.events.read_text(encoding="utf-8"))
    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(summarize(events), encoding="utf-8")
    print(f"wrote {len(events)} dispatch summaries -> {args.out}")


if __name__ == "__main__":
    main()
