#!/bin/bash
# RHA Wrapper — one-click local launcher (macOS/Linux).
# Prerequisite: Node.js 20+ (https://nodejs.org). Everything else self-installs.
cd "$(dirname "$0")"

if ! command -v node >/dev/null 2>&1; then
  echo "RHA needs Node.js 20+ — install it from https://nodejs.org and run this again."
  read -r -p "Press enter to close..."
  exit 1
fi

MAJOR=$(node -p "process.versions.node.split('.')[0]")
if [ "$MAJOR" -lt 20 ]; then
  echo "RHA needs Node.js 20+ (you have $(node -v)). Update at https://nodejs.org."
  read -r -p "Press enter to close..."
  exit 1
fi

if [ ! -d node_modules ]; then
  echo "First launch — installing dependencies (one time)…"
  npm install --no-audit --no-fund || { echo "npm install failed"; read -r -p "Press enter to close..."; exit 1; }
fi

# The bundle ships a prebuilt web UI; rebuild only if it's missing.
if [ ! -d web/dist ]; then
  npm run build:web
fi

echo "Starting RHA on http://localhost:4100 …"
( sleep 3
  open "http://localhost:4100/landing.html" 2>/dev/null \
    || xdg-open "http://localhost:4100/landing.html" 2>/dev/null ) &
npm run dev
