#!/usr/bin/env python3
"""Filter shipin3 pen boxes: keep only pen boxes overlapping a hand box.

Video 1 lesson: `marker pen` fires on white cable connectors lying on the
table (even at conf 0.79). A real pen being held must touch/overlap a hand
box in the same frame, so keep a pen box only when it overlaps a hand box:
  inter_area / pen_area >= 0.15  OR  IoU >= 0.10
Writes:
  data/out/fe165602b721/shipin3_pen_filtered.boxes.json  (rows: frame/boxes/conf/ids)
  data/out/fe165602b721/shipin3_pen_filtered.summary.json (counts + runs + top frames)
"""
import json
import os

PROJECT = "/home/agent/.claude/workspace/project"
JOB_DIR = os.path.join(PROJECT, "data", "out", "fe165602b721")
PEN_BJ = os.path.join(JOB_DIR, "shipin3_pen.boxes.json")
HAND_BJ = os.path.join(JOB_DIR, "shipin3_hand_annotated.merged.boxes.json")
OUT_BJ = os.path.join(JOB_DIR, "shipin3_pen_filtered.boxes.json")
OUT_SUM = os.path.join(JOB_DIR, "shipin3_pen_filtered.summary.json")


def area(b):
    return max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1])


def inter(a, b):
    x0, y0 = max(a[0], b[0]), max(a[1], b[1])
    x1, y1 = min(a[2], b[2]), min(a[3], b[3])
    return max(0.0, x1 - x0) * max(0.0, y1 - y0)


def main():
    pen_rows = json.load(open(PEN_BJ))
    hand_rows = json.load(open(HAND_BJ))
    hand_by_frame = {r["frame"]: (r.get("boxes") or []) for r in hand_rows}

    total_pen = 0
    kept = 0
    kept_frames = []
    out_rows = []
    for r in pen_rows:
        boxes = r.get("boxes") or []
        confs = r.get("conf") or []
        ids = r.get("ids") or []
        total_pen += len(boxes)
        hand_boxes = hand_by_frame.get(r["frame"], [])
        k_boxes, k_confs, k_ids = [], [], []
        for b, c, i in zip(boxes, confs, ids):
            pa = area(b)
            keep = False
            for hb in hand_boxes:
                ia = inter(b, hb)
                if pa > 0 and (ia / pa >= 0.15 or ia / (pa + area(hb) - ia) >= 0.10):
                    keep = True
                    break
            if keep:
                k_boxes.append(b)
                k_confs.append(c)
                k_ids.append(i)
        kept += len(k_boxes)
        if k_boxes:
            kept_frames.append(r["frame"])
        out_rows.append({"frame": r["frame"], "boxes": k_boxes, "conf": k_confs,
                         "ids": k_ids})
    json.dump(out_rows, open(OUT_BJ, "w"))

    # runs of consecutive kept frames (gap <= 2)
    runs = []
    for f in kept_frames:
        if runs and f - runs[-1][1] <= 3:
            runs[-1][1] = f
        else:
            runs.append([f, f])
    runs = [r for r in runs if r[1] - r[0] + 1 >= 2 or True]

    # top-confidence kept frames
    top = []
    for r in out_rows:
        for b, c in zip(r["boxes"], r["conf"]):
            top.append((c, r["frame"], b))
    top.sort(reverse=True)

    summary = {
        "total_pen_boxes": total_pen,
        "kept_boxes": kept,
        "frames_with_kept_pen": len(kept_frames),
        "frames_with_pen_raw": sum(1 for r in pen_rows if r.get("boxes")),
        "total_frames": len(pen_rows),
        "runs": runs,
        "top_conf": [[round(c, 2), f, [round(v) for v in b]] for c, f, b in top[:15]],
    }
    json.dump(summary, open(OUT_SUM, "w"), indent=2)
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()
