#!/usr/bin/env python3
"""Verify the generalization smoke-test job: find frames with pen boxes,
extract them from the output video, upload to OCS. Read-only on job data."""
import json, os, subprocess

FFMPEG = "/home/agent/.local/lib/python3.11/site-packages/imageio_ffmpeg/binaries/ffmpeg-linux-x86_64-v7.0.2"
BASE = "/home/agent/.claude/workspace/project/data/out"
JID = "910167c1f6d8"

d = os.path.join(BASE, JID)
print("job dir:", sorted(os.listdir(d)))
bj = mp4 = None
for f in os.listdir(d):
    if f.endswith(".boxes.json"):
        bj = os.path.join(d, f)
    elif f.endswith(".mp4") and not f.endswith(".log"):
        mp4 = os.path.join(d, f)
print("boxes.json:", bj)
print("output mp4:", mp4)
rows = json.load(open(bj))
print("frames in boxes.json:", len(rows))
print("sample row keys:", list(rows[0].keys()))
pen_frames = []
for r in rows:
    prompts = r.get("prompts") or {}
    pen = prompts.get("pen") or {}
    boxes = pen.get("boxes") or []
    if boxes:
        pen_frames.append((r["frame"], boxes, pen.get("conf", [])))
print("frames with pen boxes:", len(pen_frames))
for fr, boxes, confs in pen_frames[:6]:
    print(f"  frame {fr} t={fr/30:.1f}s pen_boxes={len(boxes)} conf={['%.2f' % c for c in confs]} boxes={[[int(v) for v in b] for b in boxes]}")
for fr, boxes, confs in pen_frames[:2]:
    out = f"/tmp/gen_smoke_pen_{fr}.jpg"
    subprocess.run([FFMPEG, "-v", "error", "-ss", str(fr / 30.0), "-i", mp4,
                    "-frames:v", "1", "-q:v", "3", "-y", out], check=True)
    r = subprocess.run(["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                        "--upload-file", out,
                        f"https://ocs.dimond.top/gen_smoke_pen_{fr}.jpg"])
    print("uploaded gen_smoke_pen_%d.jpg" % fr)
