#!/bin/bash
set -euo pipefail
# Archipelago Development Server Starter
# Pure Archipelago implementation - NO StartOS

set +e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "🚀 Archipelago Development Server Starter"
echo ""

# Use the workspace directory
FRONTEND_DIR="$PROJECT_ROOT/neode-ui"
BACKEND_DIR="$PROJECT_ROOT/core"

# Verify the frontend directory exists
if [ ! -d "$FRONTEND_DIR" ]; then
    echo "❌ Frontend directory not found: $FRONTEND_DIR"
    exit 1
fi

echo "Choose a development mode:"
echo "  1) Mock backend (UI development only - fastest)"
echo "  2) Full stack (Archipelago backend + frontend)"
echo "  3) Setup mode (first-time user setup flow - mock)"
echo "  4) Onboarding mode (onboarding flow - mock)"
echo "  5) Existing user (login with password - mock)"
echo "  6) Show manual instructions"
echo ""
read -p "Enter choice [1-6]: " choice

case $choice in
    1)
        echo ""
        echo "🎨 Starting frontend with mock backend..."
        cd "$FRONTEND_DIR"
        
        # Kill any existing processes
        echo "   🧹 Cleaning up ports 5959 and 8100..."
        lsof -ti:5959 | xargs kill -9 2>/dev/null || true
        lsof -ti:8100 | xargs kill -9 2>/dev/null || true
        sleep 1
        
        # Check dependencies
        if [ ! -d "node_modules" ]; then
            echo "⚠️  Installing dependencies..."
            npm install
        fi
        
        echo "   Running: npm run dev:mock"
        echo "   (Press Ctrl+C to stop)"
        echo ""
        npm run dev:mock
        ;;
    2)
        echo ""
        echo "🔧 Starting FULL STACK (Archipelago backend + frontend + Docker apps)..."
        
        # Kill ports
        echo "   🧹 Cleaning up ports 5959 and 8100..."
        lsof -ti:5959 | xargs kill -9 2>/dev/null || true
        lsof -ti:8100 | xargs kill -9 2>/dev/null || true
        sleep 1
        
        # Start Docker containers first
        echo ""
        echo "   🐳 Starting Docker containers..."
        if [ -f "$PROJECT_ROOT/start-docker-apps.sh" ]; then
            bash "$PROJECT_ROOT/start-docker-apps.sh"
            if [ $? -ne 0 ]; then
                echo "❌ Failed to start Docker containers."
                echo "   You can continue without Docker, but apps won't be available."
                read -p "   Continue anyway? (y/N) " -n 1 -r
                echo ""
                if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                    exit 1
                fi
            fi
        else
            echo "⚠️  start-docker-apps.sh not found, skipping Docker startup."
            echo "   Apps will not be available."
        fi
        
        echo ""
        # Check if backend can build
        echo "   🔨 Checking backend build..."
        if [ ! -d "$BACKEND_DIR" ]; then
            echo "❌ Backend directory not found: $BACKEND_DIR"
            exit 1
        fi
        
        cd "$BACKEND_DIR"
        if ! cargo check --bin archipelago > /tmp/archipelago-backend-check.log 2>&1; then
            echo "❌ Backend build check failed. See /tmp/archipelago-backend-check.log for details."
            echo "   Falling back to mock backend for UI development."
            cd "$FRONTEND_DIR"
            if [ ! -d "node_modules" ]; then
                npm install
            fi
            npm run dev:mock
            exit 0
        fi
        
        echo "   🚀 Starting Archipelago backend..."
        # Set development environment variables
        export ARCHIPELAGO_DATA_DIR=/tmp/archipelago-dev
        export ARCHIPELAGO_DEV_DATA_DIR=/tmp/archipelago-dev
        export ARCHIPELAGO_DEV_MODE=true
        export ARCHIPELAGO_BIND=127.0.0.1:5959
        export ARCHIPELAGO_LOG_LEVEL=debug
        export ARCHIPELAGO_PORT_OFFSET=10000
        export ARCHIPELAGO_BITCOIN_SIMULATION=mock
        export ARCHIPELAGO_CONTAINER_RUNTIME=docker
        
        cargo run --bin archipelago > /tmp/archipelago-backend.log 2>&1 &
        BACKEND_PID=$!
        echo "   Backend PID: $BACKEND_PID"
        echo "   Logs: tail -f /tmp/archipelago-backend.log"
        
        # Wait for backend to start listening on port 5959
        echo "   ⏳ Waiting for backend to start on port 5959..."
        timeout=60
        count=0
        while ! lsof -ti:5959 > /dev/null 2>&1 && [ $count -lt $timeout ]; do
            sleep 1
            count=$((count + 1))
        done
        
        if ! lsof -ti:5959 > /dev/null 2>&1; then
            echo "❌ Backend did not start on port 5959 within $timeout seconds."
            echo "   Killing backend process $BACKEND_PID."
            kill $BACKEND_PID 2>/dev/null || true
            echo "   Falling back to mock backend for UI development."
            cd "$FRONTEND_DIR"
            if [ ! -d "node_modules" ]; then
                npm install
            fi
            npm run dev:mock
            exit 0
        fi
        
        echo "   ✅ Backend is listening on port 5959"
        
        # Start frontend
        echo "   🎨 Starting frontend..."
        cd "$FRONTEND_DIR"
        
        if [ ! -d "node_modules" ]; then
            echo "   Installing frontend dependencies..."
            npm install
        fi
        
        # Trap to kill backend on exit (Docker containers keep running)
        trap "kill $BACKEND_PID 2>/dev/null" EXIT
        
        echo ""
        echo "   (Press Ctrl+C to stop servers)"
        echo "   💡 Docker containers will keep running. Use 'docker compose down' to stop them."
        echo ""
        npm run dev
        ;;
    3)
        echo ""
        echo "🔧 Starting in SETUP mode (mock backend)..."
        cd "$FRONTEND_DIR"
        
        # Kill ports
        lsof -ti:5959 | xargs kill -9 2>/dev/null || true
        lsof -ti:8100 | xargs kill -9 2>/dev/null || true
        sleep 1
        
        if [ ! -d "node_modules" ]; then
            npm install
        fi
        
        echo "   Starting setup flow..."
        VITE_DEV_MODE=setup npm run dev:mock
        ;;
    4)
        echo ""
        echo "📚 Starting in ONBOARDING mode (mock backend)..."
        cd "$FRONTEND_DIR"
        
        # Kill ports
        lsof -ti:5959 | xargs kill -9 2>/dev/null || true
        lsof -ti:8100 | xargs kill -9 2>/dev/null || true
        sleep 1
        
        if [ ! -d "node_modules" ]; then
            npm install
        fi
        
        echo "   Starting onboarding flow..."
        VITE_DEV_MODE=onboarding npm run dev:mock
        ;;
    5)
        echo ""
        echo "👤 Starting as EXISTING USER (mock backend)..."
        cd "$FRONTEND_DIR"
        
        # Kill ports
        lsof -ti:5959 | xargs kill -9 2>/dev/null || true
        lsof -ti:8100 | xargs kill -9 2>/dev/null || true
        sleep 1
        
        if [ ! -d "node_modules" ]; then
            npm install
        fi
        
        echo "   Starting with login screen..."
        VITE_DEV_MODE=existing npm run dev:mock
        ;;
    6)
        echo ""
        echo "📋 Manual Instructions:"
        echo ""
        echo "For UI development (mock backend):"
        echo "  cd $FRONTEND_DIR"
        echo "  npm run dev:mock"
        echo ""
        echo "For full stack (Docker apps + Archipelago backend + frontend):"
        echo "  Terminal 1 (Docker Apps):"
        echo "    cd $PROJECT_ROOT"
        echo "    ./start-docker-apps.sh"
        echo ""
        echo "  Terminal 2 (Backend):"
        echo "    cd $BACKEND_DIR"
        echo "    export ARCHIPELAGO_CONTAINER_RUNTIME=docker"
        echo "    export ARCHIPELAGO_DEV_MODE=true"
        echo "    cargo run --bin archipelago"
        echo ""
        echo "  Terminal 3 (Frontend):"
        echo "    cd $FRONTEND_DIR"
        echo "    npm run dev"
        echo ""
        echo "Then open: http://localhost:8100"
        echo ""
        echo "To stop Docker apps:"
        echo "  cd $PROJECT_ROOT"
        echo "  ./stop-docker-apps.sh"
        echo ""
        echo "Mock backend dev modes:"
        echo "  VITE_DEV_MODE=setup       - First-time setup flow"
        echo "  VITE_DEV_MODE=onboarding  - Onboarding flow"
        echo "  VITE_DEV_MODE=existing     - Login screen"
        ;;
    *)
        echo "Invalid choice"
        exit 1
        ;;
esac
