#!/usr/bin/env python3
"""Pen pass for shipin3 ONLY (Jim 2026-11-07: video 3 pen missing).

Same detection as pen_pass.py: SAM3 prompt 'marker pen', conf 0.62 /
det_thresh 0.50, on the ORIGINAL video. Writes into the shipin3 job dir:
  data/out/fe165602b721/shipin3_pen_annotated.mp4
  data/out/fe165602b721/shipin3_pen.boxes.json
Merging/filtering happens afterwards (separate step), so this only detects.

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

PROJECT = "/home/agent/.claude/workspace/project"
OUT_DIR = os.path.join(PROJECT, "data", "out")
UPLOADS = os.path.join(PROJECT, "data", "uploads")
LOG_PATH = os.path.join(PROJECT, "pen_pass_s3.log")

JOB = "fe165602b721"
STEM = "shipin3"
PROMPTS = [{"text": "marker pen", "conf": 0.62, "det_thresh": 0.50, "color": "yellow"}]


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

    job_dir = os.path.join(OUT_DIR, JOB)
    src = os.path.join(UPLOADS, f"{STEM}.mp4")
    out_mp4 = os.path.join(job_dir, f"{STEM}_pen_annotated.mp4")
    bj = os.path.join(job_dir, f"{STEM}_pen.boxes.json")
    status = os.path.join(job_dir, f"{STEM}_pen_status.json")
    try:
        log(f"[{STEM}] running SAM3 prompt='marker pen' (conf 0.62 / det_thresh 0.50)")
        hand_annotator.annotate(
            input_path=src, output_path=out_mp4, category="marker pen",
            status_path=status, prompts=PROMPTS,
            boxes_json=bj, verbose=False)
        rows = json.load(open(bj))
        total = sum(len(r.get("boxes") or []) for r in rows)
        frames_with = sum(1 for r in rows if r.get("boxes"))
        confs = sorted(c for r in rows for c in (r.get("conf") or []))
        med = confs[len(confs) // 2] if confs else None
        log(f"[{STEM}] DONE boxes={total} frames_with_pen={frames_with}/{len(rows)} "
            f"median_conf={med if med is None else round(med, 2)}")
    except Exception:
        log(f"[{STEM}] ERROR:\n{traceback.format_exc()}")
        raise


if __name__ == "__main__":
    main()
