#!/usr/bin/env python3
"""Probe: what does SAM3 return for the black honeycomb cover under the
blue battery modules in shipin3? 3-second clip at t=10s, three prompt
variants in one run, compare per-prompt boxes. No filtering yet.

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

PROMPTS = [
    {"text": "black honeycomb cover", "conf": 0.62, "det_thresh": 0.50, "color": "magenta"},
    {"text": "black cover", "conf": 0.62, "det_thresh": 0.50, "color": "cyan"},
    {"text": "black honeycomb panel", "conf": 0.62, "det_thresh": 0.50, "color": "orange"},
]


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


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

    src = os.path.join(UPLOADS, "shipin3.mp4")
    clip = os.path.join(OUT_DIR, "cap_probe_clip.mp4")
    bj = os.path.join(OUT_DIR, "cap_probe.boxes.json")
    status = os.path.join(OUT_DIR, "cap_probe_status.json")
    try:
        log("[probe] cutting 3s clip at t=10s")
        r = subprocess.run(
            [FFMPEG, "-v", "error", "-ss", "10", "-i", src,
             "-t", "3", "-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"[probe] CLIP CUT FAILED:\n{r.stderr}")
            return
        log("[probe] running SAM3 with 3 prompt variants on 90 frames")
        hand_annotator.annotate(
            input_path=clip,
            output_path=os.path.join(OUT_DIR, "cap_probe_annotated.mp4"),
            category="black honeycomb cover", status_path=status, prompts=PROMPTS,
            boxes_json=bj, verbose=False)
        rows = json.load(open(bj))
        log(f"[probe] rows={len(rows)}")
        for rw in rows[:6]:
            pr = rw.get("prompts") or {}
            line = f"frame {rw['frame']}: "
            for name, d in pr.items():
                bs = d.get("boxes") or []
                line += f"{name}={len(bs)} "
                if bs:
                    line += f"{[round(v) for v in bs[0]]} "
            log(line)
        # totals per prompt
        for name in [p["text"] for p in PROMPTS]:
            tot = 0
            fr = 0
            for rw in rows:
                bs = ((rw.get("prompts") or {}).get(name) or {}).get("boxes") or []
                tot += len(bs)
                if bs:
                    fr += 1
            log(f"[probe] TOTAL {name}: {tot} boxes on {fr}/{len(rows)} frames")
        log("[probe] DONE")
    except Exception:
        log(f"[probe] ERROR:\n{traceback.format_exc()}")


if __name__ == "__main__":
    main()
