#!/usr/bin/env python3
"""Build the full-length hand+pen+cap boxes.json for shipin3 (single render).

- Base: shipin3_hand_pen_full.boxes.json (hand/green 4326 + pen/yellow 267,
  already delivered as 视频3_hand_pen_annotated.mp4).
- Merge in: shipin3_cap_filled2.boxes.json (black honeycomb cover,
  5301 boxes on 3187/3187 frames after loose gap re-runs S1-S5 + y0>800
  junk filter). Cap boxes get labels=cap / colors=purple
  (render_from_boxes.py COLOR_MAP has purple, no magenta).
- Output: shipin3_hand_pen_cap_full.boxes.json, one row per frame.
"""
import json
import os

PROJECT = "/home/agent/.claude/workspace/project"
JOB_DIR = os.path.join(PROJECT, "data", "out", "fe165602b721")
BASE = os.path.join(JOB_DIR, "shipin3_hand_pen_full.boxes.json")
CAP = os.path.join(JOB_DIR, "shipin3_cap_fixed.boxes.json")
OUT = os.path.join(JOB_DIR, "shipin3_hand_pen_cap_full.boxes.json")


def main():
    base_rows = json.load(open(BASE))
    cap_rows = {r["frame"]: r for r in json.load(open(CAP))}
    n_cap_boxes = 0
    n_cap_frames = 0
    out = []
    for r in base_rows:
        boxes = list(r.get("boxes") or [])
        confs = list(r.get("conf") or [])
        labels = list(r.get("labels") or ["hand"] * len(boxes))
        colors = list(r.get("colors") or ["green"] * len(boxes))
        ids = list(r.get("ids") or [])
        c = cap_rows.get(r["frame"])
        if c and c.get("boxes"):
            cb = list(c["boxes"])
            cc = list(c.get("conf") or [0.0] * len(cb))
            boxes += cb
            confs += cc
            labels += ["cap"] * len(cb)
            colors += ["purple"] * len(cb)
            ids += list(c.get("ids") or [])
            n_cap_boxes += len(cb)
            n_cap_frames += 1
        out.append({"frame": r["frame"], "boxes": boxes, "conf": confs,
                    "labels": labels, "colors": colors, "ids": ids})
    json.dump(out, open(OUT, "w"))
    n_base = sum(len(r.get("boxes") or []) for r in base_rows)
    print(f"rows={len(out)} base_boxes={n_base} "
          f"cap_frames={n_cap_frames} cap_boxes={n_cap_boxes} "
          f"total={n_base + n_cap_boxes} -> {OUT}")


if __name__ == "__main__":
    main()
