#!/bin/zsh
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"

export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"

export UFORIA_DATA_ROOT="${UFORIA_DATA_ROOT:-$REPO_ROOT/data}"
export UFORIA_API_HOST="${UFORIA_API_HOST:-0.0.0.0}"
export UFORIA_DB_ENABLED="${UFORIA_DB_ENABLED:-true}"
export UFORIA_DB_DSN="${UFORIA_DB_DSN:-postgresql:///uforia?user=$USER}"
export UFORIA_DB_READ_MODE="${UFORIA_DB_READ_MODE:-db}"
export UFORIA_DB_WRITE_MODE="${UFORIA_DB_WRITE_MODE:-db}"
API_PORT="${UFORIA_API_PORT:-8000}"

if [[ -z "${UFORIA_DB_STRICT_DATASETS:-}" ]]; then
  export UFORIA_DB_STRICT_DATASETS="$(
    uv run python - <<'PY'
from uforia.contracts import API_DB_STRICT_DATASETS

print(",".join(API_DB_STRICT_DATASETS))
PY
  )"
fi

stop_requested=0
last_status=0

handle_stop() {
  stop_requested=1
}

trap handle_stop INT TERM

wait_for_port_release() {
  local pid="$1"
  local attempts=0

  while lsof -nP -iTCP:"$API_PORT" -sTCP:LISTEN -t 2>/dev/null | grep -qx "$pid"; do
    if [ "$attempts" -ge 10 ]; then
      kill -KILL "$pid" 2>/dev/null || true
      break
    fi
    sleep 1
    attempts=$((attempts + 1))
  done
}

for pid in $(lsof -nP -iTCP:"$API_PORT" -sTCP:LISTEN -t 2>/dev/null || true); do
  if [ "$pid" = "$$" ]; then
    continue
  fi

  owner="$(ps -o user= -p "$pid" | tr -d ' ')"
  if [ -z "$owner" ] || [ "$owner" != "$USER" ]; then
    echo "Refusing to stop process $pid on port $API_PORT because it is not owned by $USER." >&2
    exit 1
  fi

  echo "Stopping stale process $pid on port $API_PORT." >&2
  kill -TERM "$pid" 2>/dev/null || true
  wait_for_port_release "$pid"
done

while (( ! stop_requested )); do
  set +e
  caffeinate -i -m -s uv run uforia-api
  last_status=$?
  set -e
  if (( stop_requested )); then
    break
  fi
  echo "API exited with status $last_status, restarting in 2s." >&2
  sleep 2
done

exit "$last_status"
