#!/usr/bin/env bash
# Start Postgres, the FastAPI backend (:8000) and the Vite frontend (:5173). Ctrl+C stops both.
#
# Usage:  ./scripts/run_mac.sh          this computer only
#         ./scripts/run_mac.sh --lan    also reachable from phones on the same Wi-Fi
set -euo pipefail

LAN=false
[ "${1:-}" = "--lan" ] && LAN=true

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

if [ ! -x "$ROOT/backend/venv/bin/uvicorn" ] || [ ! -d "$ROOT/frontend/node_modules" ]; then
  echo "Setup hasn't finished yet (backend/venv or frontend/node_modules is missing)." >&2
  echo "Run this first, then try again:" >&2
  echo "  ./scripts/setup_mac.sh /path/to/Audi_db.sql --reset-db" >&2
  exit 1
fi

brew services start postgresql@18 >/dev/null 2>&1 || true

# Ports 8000 (backend) and 5173 (frontend) must be free. An earlier copy of this app
# still running is stopped automatically; anything else is reported, not killed.
for PORT in 8000 5173; do
  PIDS="$(lsof -tiTCP:$PORT -sTCP:LISTEN 2>/dev/null || true)"
  [ -z "$PIDS" ] && continue
  for PID in $PIDS; do
    CMD="$(ps -o command= -p "$PID" 2>/dev/null || true)"
    if echo "$CMD" | grep -qE "uvicorn app.main:app|vite|multiprocessing"; then
      echo "Stopping an earlier copy of the app on port $PORT (PID $PID)"
      kill "$PID" 2>/dev/null || true
    else
      echo "Port $PORT is used by another program (PID $PID): $CMD" >&2
      echo "Close it, or run: kill $PID   then start this script again." >&2
      exit 1
    fi
  done
  sleep 1
done

HOST=127.0.0.1
$LAN && HOST=0.0.0.0

cd "$ROOT/backend"
./venv/bin/uvicorn app.main:app --reload --host "$HOST" --port 8000 &
BACKEND_PID=$!
trap 'kill $BACKEND_PID 2>/dev/null || true' EXIT INT TERM

cd "$ROOT/frontend"
echo
echo "Backend:  http://localhost:8000/docs"
echo "Frontend: http://localhost:5173"
if $LAN; then
  IP="$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || true)"
  [ -n "$IP" ] && echo "Phones:   http://$IP:5173  (same Wi-Fi network)"
fi
echo
if $LAN; then
  npm run dev -- --strictPort --host
else
  npm run dev -- --strictPort
fi
