#!/usr/bin/env bash
# Background-launch the server against a scratch DB/config -- never the
# real deployment's data (see CLAUDE.md). Waits for readiness, prints
# the PID and log path. Usage: ./start-server.sh [scratch-dir] [port]
set -euo pipefail
cd "$(git -C "$(dirname "${BASH_SOURCE[0]}")" rev-parse --show-toplevel)/server"

SCRATCH="${1:-/tmp/run-server-scratch}"
PORT="${2:-8420}"
mkdir -p "$SCRATCH"

DATABASE_URL="sqlite:///$SCRATCH/test.db" \
CONFIG_PATH="$SCRATCH/config.json" \
.venv/bin/uvicorn app.main:app --host 127.0.0.1 --port "$PORT" \
  > "$SCRATCH/server.log" 2>&1 &
PID=$!
echo "$PID" > "$SCRATCH/server.pid"

for _ in $(seq 1 30); do
  curl -sf -o /dev/null "http://127.0.0.1:$PORT/" && break
  sleep 0.5
done

if ! curl -sf -o /dev/null "http://127.0.0.1:$PORT/"; then
  echo "server did not become ready -- check $SCRATCH/server.log" >&2
  exit 1
fi

echo "server PID $PID up on http://127.0.0.1:$PORT (log: $SCRATCH/server.log, db: $SCRATCH/test.db)"
