#!/usr/bin/env python3
"""Gap fill for the black honeycomb cover detection on shipin3.

Full run (conf 0.62 / det_thresh 0.50) found the cover on 2104/3187 frames
but missed long stretches (45-59s, 60-69s, 96-106s) where the cover is
smaller/higher in frame — eye-checked: the cover IS visible there, the
model just scores below threshold. This is 手段 A (loose-threshold re-run)
on the gap segments only, then:
  - drop junk boxes with y0 > 800 (bin interiors; cover never goes below ~800)
  - merge loose boxes into the main cap boxes for gap frames only
  - track-fill remaining zero gaps <= 20 frames by copying the nearest box
    (cover moves slowly; safe for <= 0.7s)

Segments (original frame numbers, with margin):
  S1 1250-1315, S2 1360-1770, S3 1780-2065, S4 2810-3186
Loose prompts: conf 0.45, det_thresh 0.35.

Writes into data/out/fe165602b721/:
  shipin3_cap_gap_<seg>.boxes.json (per-segment, rebased, filtered),
  shipin3_cap_filled.boxes.json (merged + track-filled),
  shipin3_cap_filled.summary.json

Usage (on the 19103 card):
  nohup ./run_py.sh cap_gap_detect.py > cap_gap_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.log")

PROMPTS = [{"text": "black honeycomb cover", "conf": 0.45, "det_thresh": 0.35, "color": "purple"}]
SEGMENTS = {
    "S1": (1250, 1315),
    "S2": (1360, 1770),
    "S3": (1780, 2065),
    "S4": (2810, 3186),
}
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):
    """Drop junk: boxes starting below y=800 (bin interiors) or tiny."""
    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")
    main_rows = json.load(open(os.path.join(OUT_DIR, "shipin3_cap.boxes.json")))
    main_by_frame = {r["frame"]: r for r in main_rows}

    # start from main boxes, junk-filtered
    merged = {}
    for r in main_rows:
        bs, cs = get_boxes(r)
        bs, cs = filt(bs, cs)
        merged[r["frame"]] = (bs, cs)

    for seg, (f0, f1) in SEGMENTS.items():
        try:
            clip = os.path.join(OUT_DIR, f"cap_gap_{seg}.mp4")
            bj = os.path.join(OUT_DIR, f"cap_gap_{seg}.boxes.json")
            status = os.path.join(OUT_DIR, f"cap_gap_{seg}_status.json")
            log(f"[{seg}] 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"[{seg}] CLIP CUT FAILED:\n{r.stderr}")
                continue
            log(f"[{seg}] running SAM3 loose (conf 0.45 / det 0.35)")
            hand_annotator.annotate(
                input_path=clip,
                output_path=os.path.join(OUT_DIR, f"cap_gap_{seg}_annotated.mp4"),
                category="black honeycomb cover", status_path=status, prompts=PROMPTS,
                boxes_json=bj, verbose=False)
            rows = json.load(open(bj))
            n_before = sum(1 for f in range(f0, f1 + 1) if merged.get(f, ([], []))[0])
            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
            json.dump([{"frame": rw["frame"] + f0,
                        "boxes": get_boxes(rw)[0], "conf": get_boxes(rw)[1]}
                       for rw in rows], open(bj, "w"))
            log(f"[{seg}] frames with cap: {n_before} -> {n_after}/{f1 - f0 + 1}")
        except Exception:
            log(f"[{seg}] ERROR:\n{traceback.format_exc()}")
            continue

    # track-fill remaining zero gaps <= 20 frames
    filled = 0
    frames = sorted(merged.keys())
    have = {f for f in frames if merged[f][0]}
    for f in frames:
        if merged[f][0]:
            continue
        # nearest detected frame within 20
        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 += 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_filled.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}
    json.dump(summary, open(os.path.join(OUT_DIR, "shipin3_cap_filled.summary.json"), "w"), indent=2)
    log(f"[gap] DONE total={total} boxes on {with_cap}/{len(frames)} frames, track-filled={filled}")


if __name__ == "__main__":
    main()
