#!/usr/bin/env python3
"""Draw eye-check frames for tail pen boxes: hand (green) + pen (yellow).

Reads each video's tail summary + filtered pen boxes + merged hand boxes,
draws on the TAIL clip frames, saves JPGs to pen_check_tail/ for download
and human inspection. Run on the card via ./run_py.sh (needs cv2).
"""
import json
import os

import cv2

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

VIDEOS = {
    "shipin1": {"job": "c3de403cfd15", "start_frame": 2400},
    "shipin3": {"job": "fe165602b721", "start_frame": 1800},
}


def main():
    os.makedirs(CHECK_DIR, exist_ok=True)
    for stem, cfg in VIDEOS.items():
        job, sf = cfg["job"], cfg["start_frame"]
        job_dir = os.path.join(OUT_DIR, job)
        summ_path = os.path.join(job_dir, f"{stem}_tail_pen.summary.json")
        if not os.path.exists(summ_path):
            print(f"[{stem}] no summary yet, skip")
            continue
        summary = json.load(open(summ_path))
        hand_rows = {r["frame"]: r for r in json.load(
            open(os.path.join(job_dir, f"{stem}_hand_annotated.merged.boxes.json")))}
        pen_rows = {r["frame"]: r for r in json.load(
            open(os.path.join(job_dir, f"{stem}_tail_pen_filtered.boxes.json")))}
        tail_mp4 = os.path.join(job_dir, f"{stem}_tail.mp4")

        picks = []
        for run in summary["runs"][:5]:
            picks.append(run[0])
            mid = (run[0] + run[1]) // 2
            if mid != run[0]:
                picks.append(mid)
        for c, f, b in summary["top_conf"][:3]:
            if f not in picks:
                picks.append(f)
        picks = sorted(set(picks))[:10]
        print(f"[{stem}] sample original frames: {picks}")
        if not picks:
            print(f"[{stem}] no kept pen boxes, nothing to draw")
            continue

        cap = cv2.VideoCapture(tail_mp4)
        for f in picks:
            tf = f - sf
            cap.set(cv2.CAP_PROP_POS_FRAMES, tf)
            ok, frame = cap.read()
            if not ok:
                print(f"[{stem}] frame {f} (tail {tf}): 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(CHECK_DIR, f"pen_tail_{stem}_f{f}.jpg")
            cv2.imwrite(out, frame, [cv2.IMWRITE_JPEG_QUALITY, 88])
            print(f"wrote {out}")
        cap.release()


if __name__ == "__main__":
    main()
