#!/usr/bin/env bash
set -euo pipefail

STDB_DATA_DIR=".spacetime-dev"
STDB_HOST="http://127.0.0.1:3000"
STDB_DATABASE="void-nav-dev"
MAX_WAIT=30
PIDS=()

cleanup() {
  echo ""
  echo "Shutting down..."
  for pid in "${PIDS[@]}"; do
    kill "$pid" 2>/dev/null || true
  done
  wait 2>/dev/null
  echo "Done."
  exit 0
}
trap cleanup INT TERM

rm -rf "$STDB_DATA_DIR"
mkdir -p "$STDB_DATA_DIR"

echo "[dev] Starting SpacetimeDB (data: $STDB_DATA_DIR)..."
spacetime start --data-dir "$STDB_DATA_DIR" --in-memory &
PIDS+=($!)

echo "[dev] Waiting for SpacetimeDB at $STDB_HOST ..."
waited=0
until curl -sf "$STDB_HOST/v1/health" >/dev/null 2>&1; do
  waited=$((waited + 1))
  if [ "$waited" -ge "$MAX_WAIT" ]; then
    echo "[dev] ERROR: SpacetimeDB did not start within ${MAX_WAIT}s"
    cleanup
    exit 1
  fi
  sleep 1
done
echo "[dev] SpacetimeDB is ready."

echo "[dev] Publishing module and generating bindings..."
spacetime dev --server local --delete-data -y --server-only &
PIDS+=($!)

sleep 3

echo "[dev] Starting auth server on http://localhost:4000 ..."
pnpm --filter @void-nav/auth dev &
PIDS+=($!)

echo ""
echo "=== VOID::NAV Dev Environment ==="
echo "  SpacetimeDB:  $STDB_HOST"
echo "  Auth:         http://localhost:4000"
echo "  Data dir:     $STDB_DATA_DIR (ephemeral)"
echo "  Press Ctrl+C to stop"
echo "=================================="
echo ""

wait
