#!/usr/bin/env bash
# One-glance progress for the batch run.  ./scripts/status.sh   (add -w to follow)
cd "$(dirname "$0")/.."
CLIPS=(load-0800 load-1300 load-1730 load-2200)

show() {
  printf '\n\033[1m== 批次進度  %s ==\033[0m\n' "$(date +%H:%M:%S)"

  if ps -eo args | grep -q '[r]un_batch.sh'; then
    printf '  orchestrator : \033[32m執行中\033[0m\n'
  elif grep -q "ALL DONE" logs/batch.log 2>/dev/null; then
    printf '  orchestrator : \033[32m全部完成\033[0m\n'
  else
    printf '  orchestrator : \033[31m未執行\033[0m (看 logs/batch.log)\n'
  fi

  if pgrep -x trtexec >/dev/null; then
    printf '  TensorRT     : build 中 (%s)\n' "$(ps -o etime= -C trtexec | tr -d ' ' | head -1)"
  else
    sz=$(stat -c %s /home/brad/proj/sonice-ai-sentinel-edge/.cache/roven-real-model-eval/models/dfine_s_obj2coco_onnx/model_local_b1_640.engine 2>/dev/null || echo 0)
    [ "$sz" -gt 1000000 ] && printf '  TensorRT     : engine 完成 (%s MB)\n' "$((sz/1048576))" \
                          || printf '  TensorRT     : 未產出 → 走 CPU\n'
  fi
  grep -hoE "\[batch\] (using GPU.*|using CPU.*|GPU probe: .*)" logs/batch.log 2>/dev/null | tail -2 | sed 's/^\[batch\] /  backend      : /'

  printf '\n  %-13s%-14s%-28s%s\n' 影片 抽幀 偵測 分析
  for c in "${CLIPS[@]}"; do
    nf=$(ls "media/proxies/${c}_frames" 2>/dev/null | wc -l)
    if [ -s "runs/$c/detections.jsonl" ]; then
      det="\033[32m完成\033[0m"
    elif [ -f "runs/$c/detections.jsonl.part" ]; then
      d=$(wc -l < "runs/$c/detections.jsonl.part")
      eta=$(grep -oE "eta [0-9.]+ min" "logs/detect_$c.log" 2>/dev/null | tail -1)
      det=$(printf '%d/%d  %s' "$d" "$nf" "$eta")
    else
      det="—"
    fi
    if [ -f "runs/$c/summary_v2.json" ]; then
      ana=$(python3 -c "
import json;s=json.load(open('runs/$c/summary_v2.json'))
p={}
try: p=json.load(open('metrics/${c}_phaselock.json'))
except Exception: pass
print('cycles=%d tracks=%d R=%s %s'%(s['n_cycles'],s['n_unique_tracks'],p.get('phase_R','?'),'LOCKED' if p.get('locked') else ''))" 2>/dev/null)
      ana="\033[32m$ana\033[0m"
    else
      ana="—"
    fi
    printf "  %-13s%5d/14392 " "$c" "$nf"
    printf "%-28b%b\n" "$det" "$ana"
  done

  printf '\n  網頁 : http://127.0.0.1:8765/runs/viewer_beta.html  (重新整理即可看到新資料)\n'
  printf '  紀錄 : tail -f logs/batch.log\n'
}

if [ "${1:-}" = "-w" ]; then
  while true; do clear; show; sleep 30; done
else
  show
fi
