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

# Runs the Wikipedia3D FastAPI server in the background.
# Uses a project-local venv to avoid global Python pollution.

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_DIR="$ROOT_DIR/.venv"
PID_FILE="$ROOT_DIR/.uvicorn.pid"

if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
  echo "Server already running (pid $(cat "$PID_FILE"))."
  exit 0
fi

if [[ ! -d "$VENV_DIR" ]]; then
  python3 -m venv "$VENV_DIR"
fi

# shellcheck disable=SC1091
source "$VENV_DIR/bin/activate"

pip install -r "$ROOT_DIR/server/requirements.txt" >/dev/null

nohup uvicorn server.app:app --host 0.0.0.0 --port 8088 --reload \
  >"$ROOT_DIR/uvicorn.log" 2>&1 &

echo $! > "$PID_FILE"

echo "Started Wikipedia3D FastAPI (pid $(cat "$PID_FILE"))."
