#!/bin/sh
set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PID_FILE="$SCRIPT_DIR/server.pid"
LOG_FILE="$SCRIPT_DIR/server.log"

PORT="${PORT:-8000}"
ADMIN_TOKEN="${ADMIN_TOKEN:-test-token}"

if [ -f "$PID_FILE" ]; then
  OLD_PID=$(cat "$PID_FILE")
  if kill -0 "$OLD_PID" 2>/dev/null; then
    echo "Server already running on port $PORT with PID $OLD_PID"
    echo "Open: http://127.0.0.1:$PORT/"
    exit 0
  fi
  rm -f "$PID_FILE"
fi

cd "$SCRIPT_DIR"
nohup env PORT="$PORT" ADMIN_TOKEN="$ADMIN_TOKEN" PYTHONUNBUFFERED=1 python3 server.py >> "$LOG_FILE" 2>&1 &
PID=$!
echo "$PID" > "$PID_FILE"

COUNT=0
READY=0
while kill -0 "$PID" 2>/dev/null; do
  if curl -fsS "http://127.0.0.1:$PORT/api/config" >/dev/null 2>&1; then
    READY=1
    break
  fi
  COUNT=$((COUNT + 1))
  if [ "$COUNT" -ge 20 ]; then
    break
  fi
  sleep 0.25
done

if [ "$READY" -eq 1 ]; then
  echo "Server started on port $PORT with PID $PID"
  echo "Open: http://127.0.0.1:$PORT/"
  echo "Log: $LOG_FILE"
else
  rm -f "$PID_FILE"
  echo "Server failed to start. Last log lines:"
  tail -20 "$LOG_FILE" 2>/dev/null || true
  exit 1
fi
