#!/usr/bin/env bash
# Start local dev stack: node backend (sqlite) + react frontend, server storage mode.
# Usage: ./scripts/dev-start.sh
# Stop:  ./scripts/dev-stop.sh
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p tmp data

# kill anything on the ports (zombies)
for port in 3999 4001; do
  pids=$(lsof -ti :$port 2>/dev/null || true)
  if [ -n "$pids" ]; then
    echo "port $port in use by: $pids — leaving as-is."
    echo "  (run ./scripts/dev-stop.sh first to restart clean)"
  fi
done

# backend: better-sqlite3, :4001
if ! lsof -ti :4001 >/dev/null 2>&1; then
  echo "starting backend :4001..."
  DB_PATH=$(pwd)/data/tracker.sqlite PORT=4001 ALLOW_DEV_ENDPOINTS=1 \
    nohup npm run server:dev > tmp/server.log 2>&1 &
  echo $! > tmp/server.pid
else
  echo "backend already on :4001"
fi

# frontend: server storage, :3999
if ! lsof -ti :3999 >/dev/null 2>&1; then
  # detect LAN ip so other devices (phones) can reach backend
  LAN_IP=$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || echo 127.0.0.1)
  echo "starting frontend :3999 (lan ip: $LAN_IP)..."
  NODE_ENV=development REACT_APP_DEV_TOOLS=1 \
  REACT_APP_STORAGE=server \
  REACT_APP_BACKEND_URL=http://${LAN_IP}:4001 \
  REACT_APP_BACKEND_REALTIME_URL=ws://${LAN_IP}:4001/ws \
  DANGEROUSLY_DISABLE_HOST_CHECK=true \
  HOST=0.0.0.0 \
  BROWSER=none PORT=3999 \
    nohup npm start > tmp/fe.log 2>&1 &
  echo $! > tmp/fe.pid
else
  echo "frontend already on :3999"
fi

# wait for ports to listen
echo "waiting for ports..."
for port in 4001 3999; do
  for i in {1..30}; do
    lsof -ti :$port >/dev/null 2>&1 && break
    sleep 1
  done
done

echo ""
echo "backend  : http://127.0.0.1:4001   (curl http://127.0.0.1:4001/health)"
echo "frontend : http://127.0.0.1:3999   (admin /  player /display)"
echo "lan url  : http://${LAN_IP}:3999   (phones/other devices on network)"
echo "logs     : tmp/server.log tmp/fe.log"
echo "stop     : ./scripts/dev-stop.sh"
echo ""
echo "NOTE: Prevent Sleep (wake lock) requires secure context (HTTPS/localhost)."
echo "  LAN IP (http) won't work unless Android Chrome flag set:"
echo "  chrome://flags/#unsafely-treat-insecure-origin-as-secure"
echo "  Add: http://${LAN_IP}:3999 (include port)"
