#!/bin/bash
# PgVoyager Launcher - starts server and opens browser

# Load nvm directly (don't rely on bashrc which may exit for non-interactive shells)
export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
if [ -s "$NVM_DIR/nvm.sh" ]; then
    source "$NVM_DIR/nvm.sh"
fi

# Source profile for PATH additions (profile is usually safe for non-interactive)
if [ -f "$HOME/.profile" ]; then
    source "$HOME/.profile" 2>/dev/null
fi

# Add common npm global bin paths if not already in PATH
for npm_path in "$HOME/.npm-global/bin" "$HOME/.local/bin" "$HOME/node_modules/.bin" "/usr/local/bin"; do
    if [ -d "$npm_path" ] && [[ ":$PATH:" != *":$npm_path:"* ]]; then
        export PATH="$npm_path:$PATH"
    fi
done

PGVOYAGER_BIN="${PGVOYAGER_BIN:-/usr/local/bin/pgvoyager}"

# Load port from config file if it exists
CONFIG_FILE="${HOME}/.config/pgvoyager/config"
if [ -f "${CONFIG_FILE}" ]; then
    source "${CONFIG_FILE}"
fi

# Environment variable overrides config file, default is 5137
PGVOYAGER_PORT="${PGVOYAGER_PORT:-5137}"
PGVOYAGER_URL="http://localhost:${PGVOYAGER_PORT}"

# Check if server is already responding on the port
if curl -s "${PGVOYAGER_URL}/api/version" > /dev/null 2>&1; then
    # Server already running, just open browser
    xdg-open "${PGVOYAGER_URL}" 2>/dev/null || open "${PGVOYAGER_URL}" 2>/dev/null
    exit 0
fi

# Kill any existing pgvoyager server process (but not this launcher)
pkill -f "/usr/local/bin/pgvoyager$" 2>/dev/null || true
sleep 1

# Start pgvoyager in background
PGVOYAGER_MODE=production PGVOYAGER_PORT="${PGVOYAGER_PORT}" "${PGVOYAGER_BIN}" &
PGVOYAGER_PID=$!

# Wait for server to be ready
for i in {1..30}; do
    if curl -s "${PGVOYAGER_URL}" > /dev/null 2>&1; then
        break
    fi
    sleep 0.2
done

# Open browser
xdg-open "${PGVOYAGER_URL}" 2>/dev/null || open "${PGVOYAGER_URL}" 2>/dev/null

# Keep running until the server exits
wait $PGVOYAGER_PID
