#!/usr/bin/env python3
"""Pen probe for shipin1 tail (Jim approved 2026-11-09 19:11 "direct run"):
  7s clip from 1:20 (frame 2400, t=80s) to frame 2610.
  Tests 4 new prompt variants for the white marker pen (red PAINT lettering)
  because 'marker pen' failed 2026-11-07 (boxes on white cable connectors
  and a small dark part in the upper hand; real pen in lower hand never boxed).
  Each prompt runs separately in one annotate() call; per-prompt totals logged.
  Eye-check happens afterwards via draw_pen_probe_v1.py (sampled frames).

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

PROJECT = "/home/agent/.claude/workspace/project"
JOB_DIR = os.path.join(PROJECT, "data", "out", "c3de403cfd15")
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, "pen_probe_v1.log")

PROMPTS = [
    {"text": "white marker pen", "conf": 0.62, "det_thresh": 0.50, "color": "yellow"},
    {"text": "whiteboard marker", "conf": 0.62, "det_thresh": 0.50, "color": "cyan"},
    {"text": "paint marker", "conf": 0.62, "det_thresh": 0.50, "color": "orange"},
    {"text": "white paint marker", "conf": 0.62, "det_thresh": 0.50, "color": "magenta"},
]


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, "shipin1.mp4")
    clip = os.path.join(JOB_DIR, "shipin1_pen_probe_clip.mp4")
    bj = os.path.join(JOB_DIR, "shipin1_pen_probe.boxes.json")
    status = os.path.join(JOB_DIR, "shipin1_pen_probe_status.json")
    try:
        log("[probe] cutting 7s clip from t=80s (frames 2400-2610)")
        r = subprocess.run(
            [FFMPEG, "-v", "error", "-ss", "80", "-i", src,
             "-t", "7", "-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 4 prompt variants on 210 frames")
        hand_annotator.annotate(
            input_path=clip,
            output_path=os.path.join(JOB_DIR, "shipin1_pen_probe_annotated.mp4"),
            category="pen probe", status_path=status, prompts=PROMPTS,
            boxes_json=bj, verbose=False)
        rows = json.load(open(bj))
        log(f"[probe] rows={len(rows)}")
        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")
        # sample rows with coords for the eye-check step
        for idx in (0, 105, 209):
            if idx >= len(rows):
                continue
            rw = rows[idx]
            pr = rw.get("prompts") or {}
            line = f"clip frame {rw['frame']} (orig {rw['frame'] + 2400}): "
            for name, d in pr.items():
                bs = d.get("boxes") or []
                cs = d.get("conf") or []
                if bs:
                    line += f"{name}={[[round(v) for v in b] for b in bs]} conf={[round(c, 2) for c in cs]} "
                else:
                    line += f"{name}=0 "
            log(line)
        log("[probe] DONE")
    except Exception:
        log(f"[probe] ERROR:\n{traceback.format_exc()}")


if __name__ == "__main__":
    main()
