#!/usr/bin/env bash
# Regenerate annotated TP/FP/FN frame examples for ALL 9 films against the current
# opencv5 pipeline (learned-boundary flood, shipped config). Replays each film with
# --raw-out for bboxes, then dump_error_frames.py draws GT-aware boxes
# (green TP / red FP / orange unknown / blue FN panel). Frames land in
# experiments/dump_review/<slug>/ (regenerable; gitignored). Hand-pick the ones a
# doc needs from there.
set -uo pipefail
REPO="/home/dtourolle/Development/scene-actor-extraction"; cd "$REPO"
export MIOPEN_USER_DB_PATH="$HOME/.cache/miopen-sae"
GAL=experiments/galleries/gallery_LVFace-B_Glint360K.h5
LUT=experiments/file-lut.json
CFG=(--prob-threshold 0.485 --ownership-logodds 1.72 --track-extinction-sec 31
     --track-alpha 0.435 --evidence-rho-max 0.204 --evidence-admit-below 0.784
     --match-prior 0.433 --expand-band-lo 0.804 --expand-band-hi 0.952
     --expand-gallery --presence-mode flood)
mapfile -t ROWS < <(python3 -c '
import json
for f in json.load(open("experiments/manifests/films_LVFace_opencv5.json")):
    print(f["slug"]+"\t"+f["xray"])')
SP=/tmp/claude-1000/-home-dtourolle-Development-scene-actor-extraction/c579f8cf-2974-4cbd-be88-afec68dbbf58/scratchpad
for row in "${ROWS[@]}"; do
  slug="${row%%$'\t'*}"; xray="${row#*$'\t'}"
  movie="$(python3 -c "import json;print(json.load(open('$LUT'))['$slug'])")"
  echo "=== $slug ==="
  [ -f "experiments/dump_review/$slug/manifest.json" ] && { echo "  exists, skip"; continue; }
  # replay the learned-boundary (LOO) dump so frames reflect true generalization
  dump="experiments/dumps/injected_loo/${slug}.h5"
  [ -f "$dump" ] || dump="experiments/dumps/LVFace-B_Glint360K_opencv5/dump_${slug}.h5"
  for try in 1 2 3; do
    timeout 280 python scripts/optimizer/replay.py --dump "$dump" --gallery "$GAL" \
      --out "$SP/${slug}_pred.json" --raw-out "$SP/${slug}_raw.jsonl" "${CFG[@]}" \
      >"$SP/${slug}_replay.log" 2>&1 && break
    echo "  replay try $try failed, retrying"
  done
  [ -s "$SP/${slug}_raw.jsonl" ] || { echo "  no raw output, skip"; continue; }
  python3 scripts/optimizer/dump_error_frames.py \
    --pred "$SP/${slug}_pred.json" --raw "$SP/${slug}_raw.jsonl" \
    --xray "$xray" --movie "$movie" --gallery "$GAL" \
    --out-dir "experiments/dump_review/$slug" --n-per-bucket 4 \
    >"$SP/${slug}_frames.log" 2>&1
  echo "  $(grep -oE 'wrote [0-9]+ frames' "$SP/${slug}_frames.log" | tail -1)"
done
echo "=== DONE ==="
