#!/bin/zsh
# fresh full E2E(b0ad5c18/0d30302a) 감시 — 커밋 금지.
# 3분 폴링: 전 스텝 completed → exit 0 / failed 발생 → exit 2 / 4h 타임아웃 → exit 3
PID="b0ad5c18-5140-4022-a2b0-805de0e5a385"
EID="0d30302a-51c8-4ac9-98e2-6cd9180512bf"
CK=/tmp/e2e_cookies.txt
IMG_DIR="/Users/manta/Documents/Projects/TheRoad-I1/projects/$PID"
for i in $(seq 1 80); do
  J=$(curl -s -b $CK "http://localhost:8000/api/v1/projects/$PID/episodes/$EID/steps")
  SUMMARY=$(echo "$J" | python3 -c "
import json,sys
from collections import Counter
d=json.load(sys.stdin)
steps = d if isinstance(d,list) else d.get('steps',[])
c = Counter(s.get('status') for s in steps)
run = [ (s.get('step_id') or '?') for s in steps if s.get('status')=='running']
print(json.dumps({'dist':dict(c),'running':run}, ensure_ascii=False))")
  PNGS=$(find "$IMG_DIR" -name '*.png' 2>/dev/null | wc -l | tr -d ' ')
  LINE="[$(date '+%H:%M:%S')] $SUMMARY pngs=$PNGS"
  echo "$LINE"
  echo "$LINE" >> /Users/manta/Documents/Projects/TheRoad-I1/backend/scratchpad/e2e_watch_live.log
  FAILED=$(echo "$SUMMARY" | grep -c '"failed"')
  RUNNING=$(echo "$SUMMARY" | python3 -c "
import json,sys
d=json.loads(sys.stdin.read())
dist=d['dist']
print(sum(v for k,v in dist.items() if k in ('running','pending','blocked','queued')))")
  if [ "$FAILED" -gt 0 ]; then echo "STEP FAILED — 중단"; exit 2; fi
  if [ "$RUNNING" -eq 0 ]; then echo "ALL DONE"; exit 0; fi
  sleep 180
done
echo "TIMEOUT 4h"; exit 3
