#!/usr/bin/env bash
set -euo pipefail
PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)"
ARTIFACTS="$PROJECT_ROOT/artifacts"
mkdir -p "$ARTIFACTS"
KEEP_RUNNING="${POLYFORM_DEMO_KEEP_RUNNING:-auto}"
LIVE_DEMO=0
if [[ "$KEEP_RUNNING" == "1" || ( "$KEEP_RUNNING" == "auto" && -t 1 ) ]]; then
  LIVE_DEMO=1
fi

if [[ ! -x "$PROJECT_ROOT/backend/.venv/bin/polyform-server" || ! -d "$PROJECT_ROOT/dashboard/node_modules" ]]; then
  "$PROJECT_ROOT/setup.sh"
fi
cargo build --manifest-path "$PROJECT_ROOT/rust/Cargo.toml" --locked --quiet

DEMO_DB="$ARTIFACTS/demo.db"
rm -f "$DEMO_DB" "$DEMO_DB-shm" "$DEMO_DB-wal"
POLYFORM_DB="$DEMO_DB" POLYFORM_RANDOM_SEED=polyform-demo \
  "$PROJECT_ROOT/backend/.venv/bin/polyform-server" >"$ARTIFACTS/server.log" 2>&1 &
SERVER_PID=$!
DASHBOARD_PID=""
WORKLOAD_PID=""
cleanup() {
  if [[ -n "$WORKLOAD_PID" ]]; then kill "$WORKLOAD_PID" 2>/dev/null || true; fi
  if [[ -n "$DASHBOARD_PID" ]]; then kill "$DASHBOARD_PID" 2>/dev/null || true; fi
  kill "$SERVER_PID" 2>/dev/null || true
}
trap cleanup EXIT INT TERM

for _ in {1..50}; do
  if curl --silent --fail http://127.0.0.1:8000/health >/dev/null; then break; fi
  sleep 0.1
done
curl --silent --fail http://127.0.0.1:8000/health >/dev/null || {
  echo "Backend did not start; see $ARTIFACTS/server.log" >&2
  exit 1
}

RUN_DEMO_ARGS=(--output "$ARTIFACTS/demo-results.json")
if [[ "$LIVE_DEMO" == "1" ]]; then RUN_DEMO_ARGS+=(--leave-faults-active); fi
PYTHONPATH="$PROJECT_ROOT/backend" "$PROJECT_ROOT/backend/.venv/bin/python" \
  "$PROJECT_ROOT/tools/run_demo.py" "${RUN_DEMO_ARGS[@]}"

npm run --prefix "$PROJECT_ROOT/dashboard" dev -- --host 0.0.0.0 >"$ARTIFACTS/dashboard.log" 2>&1 &
DASHBOARD_PID=$!
echo "Dashboard: http://127.0.0.1:5173"
echo "API docs:  http://127.0.0.1:8000/docs"

if [[ "$LIVE_DEMO" == "1" ]]; then
  RELEASE_ID="$($PROJECT_ROOT/backend/.venv/bin/python -c 'import json, sys; print(json.load(open(sys.argv[1]))["release_id"])' "$ARTIFACTS/demo-results.json")"
  PYTHONPATH="$PROJECT_ROOT/backend" "$PROJECT_ROOT/backend/.venv/bin/python" \
    "$PROJECT_ROOT/tools/live_workload.py" --release "$RELEASE_ID" \
    >"$ARTIFACTS/workload.log" 2>&1 &
  WORKLOAD_PID=$!
  echo "Live workloads are running. Quarantine an Investigate row to watch healthy executions change."
  echo "Press Ctrl-C to stop."
  wait "$DASHBOARD_PID"
fi
