#!/usr/bin/env python3
"""Pen pass: detect marker pens on the ORIGINAL videos (clean frames).

Runs on the 19103 card via run_py.sh. One process, imports hand_annotator.
Prompt is "marker pen" (the smoke test showed plain "pen" false-positives
on cable connectors). Default thresholds (conf 0.62 / det_thresh 0.50);
results are reviewed before merging, so a low yield is reported, not forced.

Per video writes:
  data/out/<job>/shipinN_pen_annotated.mp4  (pen-only annotated video, yellow boxes)
  data/out/<job>/shipinN_pen.boxes.json
Progress: appends one line per finished video to pen_pass.progress;
a restart skips finished videos. Merging into the hand boxes happens
afterwards (separate step), so this script only detects.

Usage:
  nohup ./run_py.sh pen_pass.py > pen_pass_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.log")
PROGRESS_PATH = os.path.join(PROJECT, "pen_pass.progress")

JOBS = {
    "shipin1": "c3de403cfd15",
    "shipin2": "4e8924d45d4b",
    "shipin3": "fe165602b721",
    "shipin4": "e9ff7e814d64",
}
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 load_progress():
    done = set()
    if os.path.exists(PROGRESS_PATH):
        for line in open(PROGRESS_PATH, encoding="utf-8"):
            line = line.strip()
            if line:
                try:
                    done.add(json.loads(line)["video"])
                except Exception:
                    pass
    return done


def main():
    sys.path.insert(0, PROJECT)
    import hand_annotator  # noqa: E402

    done = load_progress()
    log(f"[pen] starting, already done: {sorted(done)}")
    for stem in ("shipin1", "shipin2", "shipin3", "shipin4"):
        if stem in done:
            log(f"[{stem}] skipped (already done)")
            continue
        job = JOBS[stem]
        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)}")
            with open(PROGRESS_PATH, "a", encoding="utf-8") as f:
                f.write(json.dumps({"video": stem, "boxes": total,
                                    "frames_with": frames_with}) + "\n")
        except Exception:
            log(f"[{stem}] ERROR:\n{traceback.format_exc()}")
            continue
    log("[pen] ALL DONE")


if __name__ == "__main__":
    main()
