#!/usr/bin/env python3
"""Full-video black honeycomb cover detection on shipin3 (Jim 2026-11-07 17:11:
the cover is the black honeycomb panel under the blue battery modules).
Prompt 'black honeycomb cover' verified on a 3s probe clip (90/90 frames,
2 boxes/frame, eye-checked tight on both covers). Runs on the full video
(3187 frames), no hand filter — the cover is a large static structure.

Writes into data/out/fe165602b721/:
  shipin3_cap.boxes.json (raw, per-frame prompt boxes),
  shipin3_cap.summary.json

Usage (on the 19103 card):
  nohup ./run_py.sh cap_full_detect.py > cap_full_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", "fe165602b721")
UPLOADS = os.path.join(PROJECT, "data", "uploads")
LOG_PATH = os.path.join(PROJECT, "cap_full.log")

PROMPTS = [{"text": "black honeycomb cover", "conf": 0.62, "det_thresh": 0.50, "color": "magenta"}]


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

    src = os.path.join(UPLOADS, "shipin3.mp4")
    bj = os.path.join(OUT_DIR, "shipin3_cap.boxes.json")
    status = os.path.join(OUT_DIR, "shipin3_cap_status.json")
    try:
        log("[cap-full] running SAM3 prompt='black honeycomb cover' on full video (3187 frames)")
        hand_annotator.annotate(
            input_path=src,
            output_path=os.path.join(OUT_DIR, "shipin3_cap_annotated.mp4"),
            category="black honeycomb cover", status_path=status, prompts=PROMPTS,
            boxes_json=bj, verbose=False)
        rows = json.load(open(bj))
        total = 0
        frames_with = 0
        per_frame = []
        for rw in rows:
            bs = ((rw.get("prompts") or {}).get("black honeycomb cover") or {}).get("boxes") or []
            total += len(bs)
            per_frame.append(len(bs))
            if bs:
                frames_with += 1
        from collections import Counter
        dist = dict(Counter(per_frame))
        summary = {
            "video": "shipin3", "frames": len(rows),
            "total_cap_boxes": total, "frames_with_cap": frames_with,
            "boxes_per_frame_dist": dist,
        }
        json.dump(summary, open(os.path.join(OUT_DIR, "shipin3_cap.summary.json"), "w"), indent=2)
        log(f"[cap-full] DONE total={total} boxes on {frames_with}/{len(rows)} frames, dist={dist}")
    except Exception:
        log(f"[cap-full] ERROR:\n{traceback.format_exc()}")


if __name__ == "__main__":
    main()
