#!/bin/bash

# Build Dashboard Script
# This script builds the Flutter dashboard and copies the files to the server's static directory

set -e  # Exit on any error

echo "🔨 Building Flutter Dashboard..."
echo "================================"

# Check if Flutter is available
if ! command -v flutter &> /dev/null; then
    echo "❌ Flutter is not available in the system PATH"
    echo "   Please ensure Flutter is installed and available in your PATH"
    exit 1
fi

# Check if dashboard directory exists
if [ ! -d "xp_dashboard" ]; then
    echo "❌ Dashboard directory 'xp_dashboard' not found"
    echo "   Please run this script from the project root directory"
    exit 1
fi

# Build Flutter web app
echo "🚀 Running flutter build web..."
cd xp_dashboard
flutter build web --release
cd ..

# Check if build was successful
if [ ! -d "xp_dashboard/build/web" ]; then
    echo "❌ Build failed - output directory not found"
    exit 1
fi

# Create static directory if it doesn't exist
mkdir -p xp_server/lib/src/web/static

# Clear existing static files
echo "🧹 Clearing old static files..."
rm -rf xp_server/lib/src/web/static/*

# Copy new files
echo "📁 Copying new files to static directory..."
cp -r xp_dashboard/build/web/* xp_server/lib/src/web/static/

echo "✅ Dashboard build completed successfully!"
echo "   Files copied to: xp_server/lib/src/web/static/"
echo "   The server will now serve the updated Flutter dashboard"
