"""Summarize coarse trajectory signatures for traced point records."""

from __future__ import annotations

import argparse
import json
from collections import Counter
from pathlib import Path


def value_at_or_before(window: list[dict], max_ball_x: int) -> dict | None:
    candidates = [row for row in window if row.get("ball_x") is not None and row["ball_x"] <= max_ball_x]
    return candidates[-1] if candidates else None


def signature(record: dict) -> tuple:
    window = record.get("window") or []
    first_active = next((row for row in window if row.get("ball_x", 0) > 0 and row.get("ball_y", 0) > 0), None)
    x120 = value_at_or_before(window, 120)
    x150 = value_at_or_before(window, 150)
    x170 = value_at_or_before(window, 170)
    return (
        record.get("self_score"),
        record.get("opponent_score"),
        first_active.get("ball_x") if first_active else None,
        first_active.get("ball_y") if first_active else None,
        x120.get("ball_y") if x120 else None,
        x120.get("self_paddle_y") if x120 else None,
        x150.get("ball_y") if x150 else None,
        x150.get("self_paddle_y") if x150 else None,
        x170.get("ball_y") if x170 else None,
        x170.get("self_paddle_y") if x170 else None,
    )


def summarize(path: Path, pattern: str) -> dict:
    records = []
    for line in path.read_text(encoding="utf-8").splitlines():
        if not line.strip():
            continue
        record = json.loads(line)
        if pattern and record.get("pattern") != pattern:
            continue
        records.append(record)

    counts = Counter(signature(record) for record in records)
    return {
        "source": str(path),
        "pattern": pattern,
        "records": len(records),
        "signature_fields": [
            "self_score_after_point",
            "opponent_score_after_point",
            "first_active_x",
            "first_active_y",
            "x120_y",
            "x120_paddle",
            "x150_y",
            "x150_paddle",
            "x170_y",
            "x170_paddle",
        ],
        "signatures": [
            {"count": count, "values": list(values)} for values, count in counts.most_common()
        ],
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("jsonl", type=Path)
    parser.add_argument("--pattern", default="")
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

    result = summarize(args.jsonl, args.pattern)
    text = json.dumps(result, indent=2)
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(text + "\n", encoding="utf-8")
    print(text)


if __name__ == "__main__":
    main()
