#!/usr/bin/env python3
"""Merge a loose-threshold clip re-run into the original full-video boxes.json.

Usage:
  python3 merge_loose.py --orig data/out/<job>/<stem>_hand_annotated.mp4.boxes.json \
      --loose data/out/trial_*/<clip>_hand_annotated.mp4.boxes.json \
      --clip-start 271 --seg-start 331 --seg-end 745 \
      --out data/out/<job>/<stem>_hand_annotated.merged.boxes.json

Rules:
- Only clip frames whose original frame lies in [seg_start, seg_end] are merged.
- Per frame: original boxes + loose boxes, sorted by conf desc, greedy dedup
  (drop a box if IoU >= 0.5 or inner >= 0.75 vs an already-kept box).
  Original boxes win ties because they carry higher conf.
- Writes a .orig backup of the original boxes.json next to it.
- Prints how many boxes were added per frame and in total.
"""
import argparse, copy, json, os, sys


def iou(a, b):
    ax1, ay1, ax2, ay2 = a
    bx1, by1, bx2, by2 = b
    ix1, iy1 = max(ax1, bx1), max(ay1, by1)
    ix2, iy2 = min(ax2, bx2), min(ay2, by2)
    iw, ih = max(0, ix2 - ix1), max(0, iy2 - iy1)
    inter = iw * ih
    if inter <= 0:
        return 0.0, 0.0
    area_a = max(0, (ax2 - ax1)) * max(0, (ay2 - ay1))
    area_b = max(0, (bx2 - bx1)) * max(0, (by2 - by1))
    union = area_a + area_b - inter
    return inter / union if union > 0 else 0.0, inter / min(area_a, area_b) if min(area_a, area_b) > 0 else 0.0


def merge_frame(orig_boxes, orig_confs, loose_boxes, loose_confs):
    items = []
    for b, c in zip(orig_boxes, orig_confs):
        items.append((float(c), list(b), "orig"))
    for b, c in zip(loose_boxes, loose_confs):
        items.append((float(c), list(b), "loose"))
    items.sort(key=lambda x: -x[0])
    kept = []
    for conf, box, src in items:
        dup = False
        for kconf, kbox, ksrc in kept:
            ov, inner = iou(box, kbox)
            if ov >= 0.5 or inner >= 0.75:
                dup = True
                break
        if not dup:
            kept.append((conf, box, src))
    return kept


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--orig", required=True)
    ap.add_argument("--loose", required=True)
    ap.add_argument("--clip-start", type=int, required=True)
    ap.add_argument("--seg-start", type=int, required=True)
    ap.add_argument("--seg-end", type=int, required=True)
    ap.add_argument("--out", required=True)
    args = ap.parse_args()

    orig = json.load(open(args.orig))
    loose = json.load(open(args.loose))
    loose_by_frame = {r["frame"]: r for r in loose}

    total_added = 0
    frames_touched = 0
    per_frame_added = {}
    for row in orig:
        f = row["frame"]
        if not (args.seg_start <= f <= args.seg_end):
            continue
        clip_frame = f - args.clip_start
        lrow = loose_by_frame.get(clip_frame)
        if lrow is None:
            continue
        loose_boxes = lrow.get("boxes") or []
        loose_confs = lrow.get("conf") or []
        if not loose_boxes:
            continue
        before = len(row.get("boxes") or [])
        kept = merge_frame(row.get("boxes") or [], row.get("conf") or [],
                           loose_boxes, loose_confs)
        added = sum(1 for _, _, src in kept if src == "loose")
        if added:
            frames_touched += 1
            total_added += added
            per_frame_added[f] = added
            row["boxes"] = [b for _, b, _ in kept]
            row["conf"] = [c for c, _, _ in kept]
            row["ids"] = [None] * len(kept)
            row["labels"] = ["hand"] * len(kept)
            row["colors"] = ["green"] * len(kept)
            # keep grouped prompts in sync if present
            if isinstance(row.get("prompts"), dict):
                row["prompts"]["hand"] = {"boxes": row["boxes"], "conf": row["conf"], "ids": row["ids"]}

    bak = args.orig + ".orig"
    if not os.path.exists(bak):
        os.replace(args.orig, bak)
        print("backed up original to", bak)
    else:
        print("backup already exists:", bak)
    json.dump(orig, open(args.out, "w"), ensure_ascii=False)
    print("frames with new boxes added:", frames_touched)
    print("total boxes added:", total_added)
    print("per-frame added (first 20):", dict(list(per_frame_added.items())[:20]))
    print("merged boxes.json written to", args.out)


if __name__ == "__main__":
    main()
