#!/usr/bin/env python3
"""Compare trial loose run vs original run for shipin2 segment 331-745,
and extract verification frames from the trial annotated clip.
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"
ORIG_JOB = "4e8924d45d4b"
TRIAL = os.path.join(BASE, "trial_s2_seg331_745")
CLIP_START = 271
SEG = (331, 745)

def load_boxes(path):
    rows = json.load(open(path))
    return {r["frame"]: len(r.get("boxes") or []) for r in rows}

orig_path = next(os.path.join(BASE, ORIG_JOB, f) for f in os.listdir(os.path.join(BASE, ORIG_JOB)) if f.endswith(".boxes.json"))
trial_path = os.path.join(TRIAL, "shipin2_seg331_745_hand_annotated.mp4.boxes.json")
orig = load_boxes(orig_path)
trial = load_boxes(trial_path)

# per-frame comparison inside the segment
more, same, less = 0, 0, 0
orig_total = trial_total = 0
two_plus_orig = two_plus_trial = 0
for f in range(SEG[0], SEG[1] + 1):
    o = orig.get(f, 0)
    t = trial.get(f - CLIP_START, 0)
    orig_total += o
    trial_total += t
    if t > o:
        more += 1
    elif t == o:
        same += 1
    else:
        less += 1
    if o >= 2:
        two_plus_orig += 1
    if t >= 2:
        two_plus_trial += 1
print(f"segment {SEG[0]}-{SEG[1]} ({SEG[1]-SEG[0]+1} frames)")
print(f"original boxes total: {orig_total} ({orig_total/(SEG[1]-SEG[0]+1):.2f}/frame)")
print(f"loose boxes total:    {trial_total} ({trial_total/(SEG[1]-SEG[0]+1):.2f}/frame)")
print(f"added boxes: {trial_total - orig_total}")
print(f"frames where loose found MORE: {more}, same: {same}, fewer: {less}")
print(f"frames with 2+ boxes: original {two_plus_orig}, loose {two_plus_trial}")

# conf distribution of the extra boxes (loose run confs in the segment)
trial_rows = {r["frame"]: r for r in json.load(open(trial_path))}
loose_confs = []
for f in range(SEG[0], SEG[1] + 1):
    r = trial_rows.get(f - CLIP_START)
    if r:
        loose_confs.extend(r.get("conf") or [])
loose_confs.sort()
print(f"loose conf: min={loose_confs[0]:.2f} p25={loose_confs[len(loose_confs)//4]:.2f} "
      f"median={loose_confs[len(loose_confs)//2]:.2f} max={loose_confs[-1]:.2f}")
print(f"loose boxes with conf in [0.45, 0.62): {sum(1 for c in loose_confs if 0.45 <= c < 0.62)} "
      f"(these are the ones the old threshold would have dropped)")

# extract verification frames from the trial annotated clip
mp4 = os.path.join(TRIAL, "shipin2_seg331_745_hand_annotated.mp4")
for clip_frame in (89, 150, 266, 350, 450):
    out = f"/tmp/trial_s2_f{clip_frame}.jpg"
    subprocess.run([FFMPEG, "-v", "error", "-ss", str(clip_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/trial_s2_f{clip_frame}.jpg"])
    print(f"uploaded trial_s2_f{clip_frame}.jpg (orig frame {clip_frame + CLIP_START})")
