#!/usr/bin/env python3
"""Stats: original vs merged boxes.json per video (hand fix verification).
Also extracts 2 spot-check frames from rollout clip videos.
Read-only on job data (writes only /tmp jpgs)."""
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"
JOBS = {
    "shipin1": "c3de403cfd15",
    "shipin2": "4e8924d45d4b",
    "shipin3": "fe165602b721",
    "shipin4": "e9ff7e814d64",
}


def stats(path):
    rows = json.load(open(path))
    n = len(rows)
    total = sum(len(r.get("boxes") or []) for r in rows)
    two = sum(1 for r in rows if len(r.get("boxes") or []) >= 2)
    three = sum(1 for r in rows if len(r.get("boxes") or []) >= 3)
    zero = sum(1 for r in rows if len(r.get("boxes") or []) == 0)
    return n, total, total / n if n else 0, two, three, zero


for stem, jid in JOBS.items():
    d = os.path.join(BASE, jid)
    orig = os.path.join(d, f"{stem}_hand_annotated.mp4.boxes.json.orig")
    merged = os.path.join(d, f"{stem}_hand_annotated.merged.boxes.json")
    on, ot, om, o2, o3, o0 = stats(orig)
    mn, mt, mm, m2, m3, m0 = stats(merged)
    print(f"{stem}: frames={mn} boxes {ot}->{mt} (+{mt-ot}, {om:.2f}->{mm:.2f}/frame) "
          f"2+ frames {o2}->{m2}  3+ frames {o3}->{m3}  0-box {o0}->{m0}")

# spot-check: a frame from the two biggest-add clips
checks = [
    ("shipin4", "rollout_shipin4_seg2080_2354_hand_annotated.mp4", 150),
    ("shipin1", "rollout_shipin1_seg2438_2633_hand_annotated.mp4", 100),
]
for stem, fname, frame in checks:
    jid = JOBS[stem]
    mp4 = os.path.join(BASE, jid, fname)
    if not os.path.exists(mp4):
        print("missing:", mp4)
        continue
    out = f"/tmp/spot_{stem}_{frame}.jpg"
    subprocess.run([FFMPEG, "-v", "error", "-ss", str(frame / 30.0), "-i", mp4,
                    "-frames:v", "1", "-q:v", "3", "-y", out], check=True)
    subprocess.run(["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                    "--upload-file", out, f"https://ocs.dimond.top/spot_{stem}_{frame}.jpg"])
    print(f"uploaded spot_{stem}_{frame}.jpg")
