#!/usr/bin/env bash
# Capture docs/screenshots/*.png from the running POC with shared/screenshot.sh.
# Starts local mode, makes each run against Ergo with local credentials, captures the page showing
# that run, then stops the server. Run from the kit directory.
set -euo pipefail
cd "$(dirname "$0")/.."

PORT="${PORT:-8787}"
BASE="http://127.0.0.1:$PORT"
SHOT=../../shared/screenshot.sh
OUT=docs/screenshots
[ -d poc/node_modules ] || { echo "poc/node_modules not found. Run make deps first."; exit 1; }

node poc/local.mjs "$PORT" > /dev/null &
server=$!
trap 'kill "$server" 2>/dev/null || true' EXIT
for _ in $(seq 1 50); do curl -s -o /dev/null "$BASE/" && break; sleep 0.2; done

# Headless Chrome cannot wait for a slow streamed response, so the run is made here first and
# local mode replays its events to the page (see poc/local.mjs).
run_and_capture() { # <preset 1..3> <effort> <theme> <out.png>
  local body
  body=$(jq -c --argjson i "$(($1 - 1))" --arg e "$2" '{prompt: .[$i].prompt, effort: $e}' poc/web/presets.json)
  curl -s -X POST "$BASE/chat?buffered=1" -H 'Content-Type: application/json' -d "$body" | grep -q '"type":"done"' \
    || { echo "run failed for preset $1 at effort $2"; exit 1; }
  "$SHOT" "$BASE/?preset=$1&effort=$2&theme=$3&autorun=1&capture=1" "$OUT/$4"
}

"$SHOT" "$BASE/?theme=light" "$OUT/01-playground.png"
run_and_capture 1 medium light 02-lru-cache-medium.png
run_and_capture 2 high dark 03-find-the-bug-high.png
run_and_capture 3 low light 04-retry-low.png
