#!/usr/bin/env bash
# LAV Pulse launcher — usage: ./run.sh   (or: PORT=5001 ./run.sh)
set -e
cd "$(dirname "$0")"

if ! command -v node >/dev/null 2>&1; then
  echo "✗ Node.js not found."
  echo "  Install the LTS version from https://nodejs.org  (or: brew install node)"
  exit 1
fi

MAJOR=$(node -v | sed 's/^v\([0-9]*\).*/\1/')
if [ "$MAJOR" -lt 18 ]; then
  echo "✗ Node.js v18+ required (you have $(node -v)). Update at https://nodejs.org"
  exit 1
fi

if [ ! -f .env ]; then
  cp .env.example .env
  echo "• Created .env (demo mode). Edit .env + sites.config.json to connect real GA4 / OpenAI."
fi

export PORT="${PORT:-5001}"
echo "▶ Starting LAV Pulse on http://localhost:$PORT  (Ctrl+C to stop)"

# Open the browser once the server is up (macOS)
( sleep 1.2; command -v open >/dev/null 2>&1 && open "http://localhost:$PORT" ) &

exec node server/index.js
