#!/bin/bash

# CaDaR Documentation Build Script
# This script builds and deploys the modern Docusaurus documentation

set -e  # Exit on error

echo "════════════════════════════════════════════════════"
echo "  CaDaR Documentation Build Script"
echo "════════════════════════════════════════════════════"
echo ""

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "❌ Error: Node.js is not installed"
    echo "Please install Node.js from https://nodejs.org/"
    exit 1
fi

echo "✓ Node.js version: $(node --version)"

# Check if npm is installed
if ! command -v npm &> /dev/null; then
    echo "❌ Error: npm is not installed"
    echo "Please install npm (comes with Node.js)"
    exit 1
fi

echo "✓ npm version: $(npm --version)"

# Navigate to docs directory
cd "$(dirname "$0")/cadar-docs"

# Check if package.json exists in the docs directory (not the parent)
if [ ! -f "cadar-docs/package.json" ] && [ ! -f "package.json" ]; then
    echo "❌ Error: package.json not found in cadar-docs directory"
    exit 1
fi

# Check if package.json exists
if [ ! -f "package.json" ]; then
    echo "❌ Error: package.json not found"
    exit 1
fi

# Install dependencies if node_modules doesn't exist
if [ ! -d "node_modules" ]; then
    echo "📦 Installing dependencies..."
    npm install
    echo "✓ Dependencies installed"
else
    echo "✓ Dependencies already installed"
fi

echo ""
echo "🔨 Building documentation..."
npm run build

# Check if build was successful
if [ ! -d "build" ]; then
    echo "❌ Error: Build failed - no build directory created"
    exit 1
fi

echo "✓ Documentation built successfully!"
echo "📁 Build location: $(pwd)/build"

# Optional: Serve locally for preview
if [ "$1" = "--serve" ]; then
    echo ""
    echo "🌐 Starting local server..."
    echo "  Documentation will be available at: http://localhost:3000"
    echo "  Press Ctrl+C to stop the server"
    echo ""
    npm run serve
fi

# Optional: Deploy to GitHub Pages
if [ "$1" = "--deploy" ]; then
    echo ""
    echo "🚀 Deploying to GitHub Pages..."
    npm run deploy
    echo "✓ Deployed to GitHub Pages!"
fi

echo ""
echo "════════════════════════════════════════════════════"
echo "  Build completed successfully!"
echo "════════════════════════════════════════════════════"
echo ""
echo "Next steps:"
echo "  1. Preview locally:"
echo "     ./build-docs.sh --serve"
echo ""
echo "  2. Deploy to GitHub Pages:"
echo "     ./build-docs.sh --deploy"
echo ""