#!/usr/bin/env bash
set -u
COOKIES=/Users/manta/Documents/Projects/TheRoad-I1/logs/cookies_8014.txt
PID=4f948193-6809-4ae3-a3c6-2ca4e8af1c1a
EID=dc70c0b3-5c09-4664-8c0f-9cac38c0c6ca
LOG=/Users/manta/Documents/Projects/TheRoad-I1/logs/poll_e2e.log
echo "=== poll start $(date +%H:%M:%S) ===" > "$LOG"
for i in $(seq 1 200); do
  ts=$(date +%H:%M:%S)
  curl -s -b "$COOKIES" "http://localhost:8014/api/v1/projects/$PID/episodes/$EID/steps" -o /tmp/steps.json
  python3 <<'PY' >> "$LOG"
import json
try:
  with open('/tmp/steps.json') as f: d=json.load(f)
  steps=d.get('steps') if isinstance(d,dict) else d
  from collections import Counter
  c=Counter(s.get('status','?') for s in steps)
  running=[s['step_id'] for s in steps if s.get('status')=='running']
  failed=[s['step_id'] for s in steps if s.get('status') in ('failed','error')]
  partial=[s['step_id'] for s in steps if s.get('status')=='partial']
  done_n=c.get('completed',0)+c.get('success',0)+c.get('done',0)
  total=len(steps)
  print(f"iter={__import__('os').environ.get('I','?')} {dict(c)} done={done_n}/{total} running={running} failed={failed} partial={partial}")
except Exception as e:
  print('ERR', e)
PY
  echo "  -- iter=$i ts=$ts" >> "$LOG"
  # check terminal
  TERMINAL=$(python3 -c "
import json
with open('/tmp/steps.json') as f: d=json.load(f)
steps=d.get('steps') if isinstance(d,dict) else d
running=[s for s in steps if s.get('status') in ('running','pending','blocked','queued')]
print('done' if not running else 'live')
")
  if [ "$TERMINAL" = "done" ]; then
    echo "=== terminal reached @$(date +%H:%M:%S) iter=$i ===" >> "$LOG"
    break
  fi
  sleep 60
done
echo "=== poll end $(date +%H:%M:%S) ===" >> "$LOG"
