#!/usr/bin/env bash
# Phase A1 v2 pipeline. Detection is CACHED, so this whole chain runs in well
# under a minute -- the 25-40 min D-FINE pass only has to happen when the frame
# set itself changes (see build_detections_cache.py).
#
#   a1_features  frames + cached detections -> saturation glass signal, appearance
#   a1_retrack   cached detections          -> stitched identities
#   a1_events    tracks + glass             -> zones, occupancy, cycles
#   a1_metrics   run + station GT           -> metrics
#
# Skip step 1 with SKIP_FEATURES=1 when only tuning tracking / zones / cycles;
# that is the fast loop and takes ~15 s.
set -euo pipefail
cd "$(dirname "$0")/.."

RUN=runs/phase_a1_pilot
ZONES=configs/shengmuglass-tempering-load.zones.v2.json
GT=data/gt_a1_0930_1030.station.json
mkdir -p logs metrics

if [[ ! -f $RUN/detections.jsonl ]]; then
  echo "== rebuilding detection cache from tracks.jsonl"
  python3 scripts/build_detections_cache.py --tracks $RUN/tracks.jsonl --out $RUN/detections.jsonl
fi

if [[ ! -f $GT ]]; then
  echo "== deriving station GT"
  python3 scripts/a1_fix_gt.py --gt-json data/gt_a1_0930_1030.json --out $GT
fi

if [[ "${SKIP_FEATURES:-0}" != "1" ]]; then
  echo "== 1/4 frame features (saturation glass signal + appearance)  ~3 min"
  python3 scripts/a1_features.py \
    --frames-dir media/proxies/a1_frames --detections $RUN/detections.jsonl \
    --zones $ZONES --out-dir $RUN 2>&1 | tee logs/a1_features.log
fi

echo "== 2/4 re-track"
python3 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 "== 3/4 zones / occupancy / cycles"
python3 scripts/a1_events.py --tracks $RUN/tracks_v2.jsonl --glass $RUN/glass_bands.json \
  --zones $ZONES --out-dir $RUN --video-t0 5400

echo "== 4/4 metrics"
python3 scripts/a1_metrics.py --run-dir $RUN --gt-station $GT --out metrics/phase_a1_v2.json

echo
echo "viewer: http://127.0.0.1:8765/$RUN/viewer.html    (python3 -m http.server 8765)"
