#!/usr/bin/env python3
"""Fix the too-tall left-cover boxes in shipin3_cap_filled2.boxes.json.

Defect (eye-checked on f2400/f3000): in the loose re-run segments S4/S5
(and a few strict frames), the LEFT cover box extends up to y0=0, covering
the whole blue module instead of just the black cover below it. The box's
x-range and y1 (bottom) are correct; only y0 is wrong. 667 boxes affected,
all in frames that also have a good (in-band) box — the right cover, which
sits at the same height. Fix: borrow the good box's y0/y1 for each bad box
in the same frame (keep the bad box's own x0/x1). Fallback: nearest frame's
good y-band.

Writes: shipin3_cap_fixed.boxes.json + summary.
"""
import json
import os

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


def main():
    rows = json.load(open(SRC))
    n_fixed = 0
    # precompute per-frame good y-band (widest good box)
    band = {}
    for r in rows:
        good = [b for b in (r.get("boxes") or []) if b[1] >= 200]
        if good:
            g = max(good, key=lambda b: b[2] - b[0])
            band[r["frame"]] = (g[1], g[3])
    frames = sorted(band.keys())
    for r in rows:
        f = r["frame"]
        boxes = r.get("boxes") or []
        confs = r.get("conf") or []
        new_boxes = []
        for b in boxes:
            if b[1] < 200:
                ref = band.get(f)
                if ref is None:
                    # nearest frame with a band
                    prev_f = max([h for h in frames if h < f], default=None)
                    next_f = min([h for h in frames if h > f], default=None)
                    cands = [(abs(f - pf), pf) for pf in (prev_f, next_f) if pf is not None]
                    ref = band[min(cands)[1]] if cands else None
                if ref is not None:
                    b = [b[0], ref[0], b[2], ref[1]]
                    n_fixed += 1
            new_boxes.append(b)
        r["boxes"] = new_boxes
    json.dump(rows, open(OUT, "w"))
    total = sum(len(r.get("boxes") or []) for r in rows)
    with_cap = sum(1 for r in rows if r.get("boxes"))
    bad_left = sum(1 for r in rows for b in (r.get("boxes") or []) if b[1] < 200)
    print(f"rows={len(rows)} total_cap_boxes={total} frames_with_cap={with_cap} "
          f"fixed={n_fixed} bad_y0_left={bad_left} -> {OUT}")


if __name__ == "__main__":
    main()
