#!/usr/bin/env python3
"""Extract raw per-frame detections from an existing tracks.jsonl into detections.jsonl.

The detector pass is the expensive part of Phase A1 (~25-40 min on CPU). Every
tracker / zone / cycle experiment re-ran it for no reason. ByteTrack emits one
output box per activated track and starts a new track for any detection it fails
to match, so the tracked boxes in tracks.jsonl are a faithful copy of the
detector output above the activation threshold -- enough to replay tracking
offline in seconds.
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--tracks", required=True)
    ap.add_argument("--out", required=True)
    args = ap.parse_args()

    n_det = 0
    with Path(args.tracks).open(encoding="utf-8") as fh, Path(args.out).open("w", encoding="utf-8") as out:
        for line in fh:
            rec = json.loads(line)
            dets = [
                {"bbox_xyxy": p["bbox_xyxy"], "confidence": p.get("confidence", 0.0)}
                for p in rec.get("people", [])
            ]
            n_det += len(dets)
            out.write(
                json.dumps(
                    {"t_local": rec["t_local"], "t_abs": rec["t_abs"], "detections": dets},
                    ensure_ascii=False,
                )
                + "\n"
            )
    print(f"wrote {args.out}: {n_det} detections")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
