#!/bin/bash
#
# AtlasOS - Calypso Frontend Test Script
# Tests the frontend application
#

set -euo pipefail

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

echo "=========================================="
echo "Calypso Frontend Test Script"
echo "=========================================="
echo ""

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "❌ Node.js is not installed"
    echo ""
    echo "Please install Node.js 18+ first:"
    echo "  Option 1: Run the install script:"
    echo "    sudo ./scripts/install-requirements.sh"
    echo ""
    echo "  Option 2: Install manually:"
    echo "    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -"
    echo "    sudo apt-get install -y nodejs"
    echo ""
    exit 1
fi

NODE_VERSION=$(node --version)
NPM_VERSION=$(npm --version)

echo "✅ Node.js: $NODE_VERSION"
echo "✅ npm: $NPM_VERSION"
echo ""

# Check Node.js version (should be 18+)
NODE_MAJOR=$(echo "$NODE_VERSION" | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_MAJOR" -lt 18 ]; then
    echo "⚠️  Warning: Node.js version should be 18 or higher (found: $NODE_VERSION)"
    echo ""
fi

# Check if backend is running
echo "Checking if backend API is running..."
if curl -s http://localhost:8080/api/v1/health > /dev/null 2>&1; then
    echo "✅ Backend API is running on http://localhost:8080"
else
    echo "⚠️  Warning: Backend API is not running on http://localhost:8080"
    echo "   The frontend will still work, but API calls will fail"
    echo "   Start the backend with:"
    echo "     cd backend && go run ./cmd/calypso-api -config config.yaml.example"
    echo ""
fi

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

cd "$FRONTEND_DIR"

# Check if node_modules exists
if [ ! -d "node_modules" ]; then
    echo "📦 Installing dependencies..."
    echo ""
    npm install
    echo ""
else
    echo "✅ Dependencies already installed"
    echo ""
fi

# Check if build works
echo "🔨 Testing build..."
if npm run build; then
    echo "✅ Build successful"
    echo ""
else
    echo "❌ Build failed"
    exit 1
fi

echo "=========================================="
echo "✅ Frontend test complete!"
echo "=========================================="
echo ""
echo "To start the development server:"
echo "  cd frontend"
echo "  npm run dev"
echo ""
echo "The frontend will be available at:"
echo "  http://localhost:3000"
echo ""
echo "Make sure the backend is running on:"
echo "  http://localhost:8080"
echo ""

