#!/bin/bash
# Nitrous Customer Database Explorer launcher
# Double-click this file to start the server + open in browser

cd "$(dirname "$0")"

PORT=8765
URL="http://localhost:$PORT/Database-Explorer.html"

# If something else is on the port, pick another
while lsof -i ":$PORT" >/dev/null 2>&1; do
  PORT=$((PORT+1))
  URL="http://localhost:$PORT/Database-Explorer.html"
done

# Start server in background
echo ""
echo "═══════════════════════════════════════════════════════════"
echo "  NITROUS · Customer Intelligence Explorer"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "  ▸ Starting local server on port $PORT..."
python3 -m http.server $PORT --bind 127.0.0.1 >/tmp/explorer-server.log 2>&1 &
SERVER_PID=$!

sleep 1

# Try to open in browser
echo "  ▸ Opening in browser..."
if command -v xdg-open >/dev/null 2>&1; then
  xdg-open "$URL" >/dev/null 2>&1
elif command -v open >/dev/null 2>&1; then
  open "$URL"
elif command -v firefox >/dev/null 2>&1; then
  firefox "$URL" >/dev/null 2>&1 &
elif command -v google-chrome >/dev/null 2>&1; then
  google-chrome "$URL" >/dev/null 2>&1 &
else
  echo "  ⚠ Could not auto-open browser. Visit: $URL"
fi

echo ""
echo "  ✓ Server running. Page open at:"
echo "    $URL"
echo ""
echo "  Press Ctrl+C in this window to stop the server."
echo "═══════════════════════════════════════════════════════════"
echo ""

# Keep running until user kills with Ctrl+C
trap "echo ''; echo '  Stopping server...'; kill $SERVER_PID 2>/dev/null; exit" INT TERM
wait $SERVER_PID
