#!/usr/bin/env python3
"""Eye-check for pen probe v1: draw each prompt's boxes on sampled clip
frames and save JPGs. Picks 5 frames that actually have boxes (spread over
the clip) so the verdict is based on real detections, not empty frames.

Usage (on the 19103 card):
  ./run_py.sh draw_pen_probe_v1.py
Outputs: data/out/c3de403cfd15/pen_probe_v1_f<clip>_<orig>.jpg
"""
import json
import os
import sys

PROJECT = "/home/agent/.claude/workspace/project"
JOB_DIR = os.path.join(PROJECT, "data", "out", "c3de403cfd15")

COLORS = {
    "white marker pen": (0, 255, 255),      # yellow BGR
    "whiteboard marker": (255, 255, 0),     # cyan BGR
    "paint marker": (0, 165, 255),          # orange BGR
    "white paint marker": (255, 0, 255),    # magenta BGR
}
NAMES = list(COLORS.keys())


def main():
    import cv2  # noqa: F401  (imported via run_py.sh env)

    bj = os.path.join(JOB_DIR, "shipin1_pen_probe.boxes.json")
    clip = os.path.join(JOB_DIR, "shipin1_pen_probe_clip.mp4")
    rows = json.load(open(bj))
    by_frame = {r["frame"]: r for r in rows}

    # frames that have at least one box for the three live prompts
    live = [p for p in NAMES if p != "whiteboard marker"]
    cand = []
    for r in rows:
        pr = r.get("prompts") or {}
        if any(((pr.get(p) or {}).get("boxes")) for p in live):
            cand.append(r["frame"])
    print(f"frames with boxes: {len(cand)} of {len(rows)}, first={cand[:3]} last={cand[-3:]}")
    # spread 5 across candidates
    picks = []
    for q in (0.05, 0.3, 0.5, 0.7, 0.95):
        picks.append(cand[min(len(cand) - 1, int(q * len(cand)))])
    picks = sorted(set(picks))
    print(f"picks (clip frames): {picks}")

    cap = cv2.VideoCapture(clip)
    for f in picks:
        cap.set(cv2.CAP_PROP_POS_FRAMES, f)
        ok, img = cap.read()
        if not ok:
            print(f"frame {f}: READ FAILED")
            continue
        r = by_frame[f]
        pr = r.get("prompts") or {}
        for name in NAMES:
            for b in ((pr.get(name) or {}).get("boxes") or []):
                x0, y0, x1, y1 = [int(v) for v in b]
                cv2.rectangle(img, (x0, y0), (x1, y1), COLORS[name], 4)
                cv2.putText(img, name, (x0, max(0, y0 - 8)),
                            cv2.FONT_HERSHEY_SIMPLEX, 1.0, COLORS[name], 3)
        out = os.path.join(JOB_DIR, f"pen_probe_v1_f{f}_{f + 2400}.jpg")
        cv2.imwrite(out, img, [cv2.IMWRITE_JPEG_QUALITY, 88])
        print(f"wrote {out}")
    cap.release()
    print("DONE")


if __name__ == "__main__":
    main()
