#!/usr/bin/env python3
"""S5 follow-up: the one remaining cap gap after cap_gap_detect.py —
frames 2283-2542 (t=76.1-84.7s). The strict run found ONLY junk boxes
(y0>800, bin interiors) there, so the y0 filter zeroed the whole stretch;
the cover IS visible (eye-checked f2400). Loose re-run, same filter,
merge into shipin3_cap_filled.boxes.json, track-fill leftovers <= 20.

Writes into data/out/fe165602b721/:
  cap_gap_S5.boxes.json, shipin3_cap_filled2.boxes.json,
  shipin3_cap_filled2.summary.json

Usage (on the 19103 card):
  nohup ./run_py.sh cap_gap_s5.py > cap_gap_s5_stdout.log 2>&1 &
"""
import json
import os
import subprocess
import sys
import traceback

PROJECT = "/home/agent/.claude/workspace/project"
OUT_DIR = os.path.join(PROJECT, "data", "out", "fe165602b721")
UPLOADS = os.path.join(PROJECT, "data", "uploads")
FFMPEG = "/home/agent/.local/lib/python3.11/site-packages/imageio_ffmpeg/binaries/ffmpeg-linux-x86_64-v7.0.2"
LOG_PATH = os.path.join(PROJECT, "cap_gap_s5.log")

PROMPTS = [{"text": "black honeycomb cover", "conf": 0.45, "det_thresh": 0.35, "color": "purple"}]
F0, F1 = 2280, 2545
FPS = 30.0


def log(msg):
    print(msg, flush=True)
    with open(LOG_PATH, "a", encoding="utf-8") as f:
        f.write(msg + "\n")


def get_boxes(row):
    d = ((row.get("prompts") or {}).get("black honeycomb cover") or {})
    return d.get("boxes") or [], d.get("conf") or []


def filt(boxes, confs):
    out_b, out_c = [], []
    for b, c in zip(boxes, confs):
        w, h = b[2] - b[0], b[3] - b[1]
        if b[1] > 800 or w < 60 or h < 30:
            continue
        out_b.append(b)
        out_c.append(c)
    return out_b, out_c


def main():
    sys.path.insert(0, PROJECT)
    import hand_annotator  # noqa: E402

    src = os.path.join(UPLOADS, "shipin3.mp4")
    filled = json.load(open(os.path.join(OUT_DIR, "shipin3_cap_filled.boxes.json")))
    merged = {r["frame"]: (r.get("boxes") or [], r.get("conf") or []) for r in filled}
    try:
        clip = os.path.join(OUT_DIR, "cap_gap_S5.mp4")
        bj = os.path.join(OUT_DIR, "cap_gap_S5.boxes.json")
        status = os.path.join(OUT_DIR, "cap_gap_S5_status.json")
        log(f"[S5] cutting clip frames {F0}-{F1} ({F1 - F0 + 1} frames)")
        r = subprocess.run(
            [FFMPEG, "-v", "error", "-ss", str(F0 / FPS), "-i", src,
             "-t", str((F1 - F0 + 1) / FPS), "-r", "30",
             "-c:v", "libx264", "-crf", "18", "-preset", "veryfast",
             "-c:a", "aac", "-y", clip],
            capture_output=True, text=True)
        if r.returncode != 0:
            log(f"[S5] CLIP CUT FAILED:\n{r.stderr}")
            return
        log("[S5] running SAM3 loose (conf 0.45 / det 0.35)")
        hand_annotator.annotate(
            input_path=clip,
            output_path=os.path.join(OUT_DIR, "cap_gap_S5_annotated.mp4"),
            category="black honeycomb cover", status_path=status, prompts=PROMPTS,
            boxes_json=bj, verbose=False)
        rows = json.load(open(bj))
        n_after = 0
        for rw in rows:
            oframe = rw["frame"] + F0
            if oframe > F1:
                continue
            bs, cs = get_boxes(rw)
            bs, cs = filt(bs, cs)
            if bs:
                merged[oframe] = (bs, cs)
                n_after += 1
        log(f"[S5] frames with cap: {n_after}/{F1 - F0 + 1}")

        # track-fill remaining zero gaps <= 20 frames
        frames = sorted(merged.keys())
        have = {f for f in frames if merged[f][0]}
        filled_n = 0
        for f in frames:
            if merged[f][0]:
                continue
            prev_f = max([h for h in have if h < f], default=None)
            next_f = min([h for h in have if h > f], default=None)
            cands = [(abs(f - pf), pf) for pf in (prev_f, next_f) if pf is not None]
            if not cands:
                continue
            d, nf = min(cands)
            if d <= 20:
                merged[f] = merged[nf]
                filled_n += 1
        out_rows = [{"frame": f, "boxes": merged[f][0], "conf": merged[f][1]}
                    for f in frames]
        json.dump(out_rows, open(os.path.join(OUT_DIR, "shipin3_cap_filled2.boxes.json"), "w"))
        total = sum(len(b) for b, _ in merged.values())
        with_cap = sum(1 for b, _ in merged.values() if b)
        summary = {"video": "shipin3", "frames": len(frames),
                   "total_cap_boxes": total, "frames_with_cap": with_cap,
                   "track_filled_frames": filled_n}
        json.dump(summary, open(os.path.join(OUT_DIR, "shipin3_cap_filled2.summary.json"), "w"), indent=2)
        log(f"[S5] DONE total={total} boxes on {with_cap}/{len(frames)} frames, track-filled={filled_n}")
    except Exception:
        log(f"[S5] ERROR:\n{traceback.format_exc()}")


if __name__ == "__main__":
    main()
