#!/usr/bin/env python3
"""Extra eye-check frames inside shipin3's long pen run (1827-2093).
Draws hand (green) + filtered pen (yellow) on the tail clip for the given
original frame numbers. Run on the card via ./run_py.sh (needs cv2).
"""
import json
import os
import sys

import cv2

PROJECT = "/home/agent/.claude/workspace/project"
JOB_DIR = os.path.join(PROJECT, "data", "out", "fe165602b721")
OUT_DIR = os.path.join(PROJECT, "pen_check_tail")
START_FRAME = 1800


def main():
    frames = [int(x) for x in sys.argv[1:]] or [1850, 1900, 2000, 2050]
    hand_rows = {r["frame"]: r for r in json.load(
        open(os.path.join(JOB_DIR, "shipin3_hand_annotated.merged.boxes.json")))}
    pen_rows = {r["frame"]: r for r in json.load(
        open(os.path.join(JOB_DIR, "shipin3_tail_pen_filtered.boxes.json")))}
    tail_mp4 = os.path.join(JOB_DIR, "shipin3_tail.mp4")
    cap = cv2.VideoCapture(tail_mp4)
    for f in frames:
        cap.set(cv2.CAP_PROP_POS_FRAMES, f - START_FRAME)
        ok, frame = cap.read()
        if not ok:
            print(f"frame {f}: read failed")
            continue
        h = hand_rows.get(f, {})
        for b, c in zip(h.get("boxes") or [], h.get("conf") or []):
            x0, y0, x1, y1 = [int(v) for v in b]
            cv2.rectangle(frame, (x0, y0), (x1, y1), (0, 200, 0), 3)
            cv2.putText(frame, f"hand {c:.2f}", (x0, max(0, y0 - 8)),
                        cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 200, 0), 2)
        p = pen_rows.get(f, {})
        for b, c in zip(p.get("boxes") or [], p.get("conf") or []):
            x0, y0, x1, y1 = [int(v) for v in b]
            cv2.rectangle(frame, (x0, y0), (x1, y1), (0, 220, 220), 3)
            cv2.putText(frame, f"pen {c:.2f}", (x0, max(0, y0 - 8)),
                        cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 220, 220), 2)
        out = os.path.join(OUT_DIR, f"pen_tail_shipin3_f{f}.jpg")
        cv2.imwrite(out, frame, [cv2.IMWRITE_JPEG_QUALITY, 88])
        print(f"wrote {out}")
    cap.release()


if __name__ == "__main__":
    main()
