#!/usr/bin/env bash
# Full-clip pipeline for one 4 h video, downstream of cached detection.
#   ./scripts/run_clip.sh load-1300
# Detection must already exist at runs/<clip>/detections.jsonl (detect_clip.py).
# Everything here replays from that cache, so re-tuning is minutes, not hours.
set -euo pipefail
cd "$(dirname "$0")/.."

CLIP="$1"
PY=/home/brad/proj/sonice-ai-sentinel-edge/.cache/roven-real-model-eval/venv/bin/python
RUN=runs/$CLIP
FRAMES=media/proxies/${CLIP}_frames
ZONES=configs/shengmuglass-tempering-load.zones.v2.json
FUR=data/furnace_20260617.json
mkdir -p "$RUN" metrics logs

[[ -f $RUN/detections.jsonl ]] || { echo "missing $RUN/detections.jsonl - run detect_clip.py first"; exit 1; }

echo "== [$CLIP] 1/4 frame features"
$PY scripts/a1_features.py --frames-dir "$FRAMES" --detections "$RUN/detections.jsonl" \
  --zones "$ZONES" --out-dir "$RUN" --segments 16

echo "== [$CLIP] 2/4 re-track"
$PY scripts/a1_retrack.py --detections "$RUN/detections.jsonl" --appearance "$RUN/appearance.npz" \
  --zones "$ZONES" --out "$RUN/tracks_v2.jsonl" --report "$RUN/track_report.json"

echo "== [$CLIP] 3/4 zones / occupancy / cycles"
$PY scripts/a1_events.py --tracks "$RUN/tracks_v2.jsonl" --glass "$RUN/glass_bands.json" \
  --zones "$ZONES" --out-dir "$RUN" --video-t0 0

echo "== [$CLIP] 4/4 phase lock vs furnace log"
NF=$(ls "$FRAMES" | wc -l)
$PY scripts/a1_phase_metric.py --cycles "$RUN/load_cycles_v2.json" --furnace "$FUR" \
  --clip "$CLIP" --video-t0 0 --win-start 0 --win-end "$NF" --key t_start \
  --out "metrics/${CLIP}_phaselock.json"
echo "== [$CLIP] done"
