#!/bin/bash

# SamCloud FileBrowser - Automatic Live Development
echo "🚀 SamCloud FileBrowser - Auto-Reload Development Mode"
echo "====================================================="

PROJECT_DIR="/Volumes/SamMgmt/Containers/SamCloud FileBrowser"
CSS_FILE="$PROJECT_DIR/src/frontend/src/css/_samcloud.css"
CONTAINER_NAME="samcloud-filebrowser"

echo "📁 Project: $PROJECT_DIR"
echo "🎨 Watching: $CSS_FILE"
echo "🐳 Container: $CONTAINER_NAME"
echo ""

# Function to rebuild CSS and update container
update_css() {
    echo "🔄 CSS changed! Rebuilding..."
    
    cd "$PROJECT_DIR/src/frontend"
    
    # Quick CSS build
    echo "📦 Building CSS..."
    npx vite build --mode development >/dev/null 2>&1
    
    if [ $? -eq 0 ]; then
        echo "✅ CSS built successfully"
        
        # Restart container to pickup changes
        echo "🔄 Restarting container..."
        cd "$PROJECT_DIR"
        docker-compose restart >/dev/null 2>&1
        
        if [ $? -eq 0 ]; then
            echo "✅ Container restarted - changes are live!"
            echo "🌐 View: http://localhost:8383"
        else
            echo "❌ Failed to restart container"
        fi
    else
        echo "❌ CSS build failed"
    fi
    
    echo ""
}

# Check if container is running
if ! docker ps | grep -q $CONTAINER_NAME; then
    echo "🚀 Starting container..."
    cd "$PROJECT_DIR"
    docker-compose up -d >/dev/null 2>&1
    echo "✅ Container started"
fi

echo "👁️  Watching for CSS changes..."
echo "📝 Edit $CSS_FILE and see changes automatically!"
echo "🛑 Press Ctrl+C to stop"
echo ""

# Initial update
update_css

# Watch for changes using fswatch or fallback to polling
if command -v fswatch >/dev/null 2>&1; then
    echo "📡 Using fswatch for optimal performance"
    fswatch -1 "$CSS_FILE" | while read; do
        update_css
    done
else
    echo "📡 Using file polling (install fswatch for better performance)"
    echo "   💡 brew install fswatch"
    
    LAST_MODIFIED=0
    
    while true; do
        if [ -f "$CSS_FILE" ]; then
            CURRENT_MODIFIED=$(stat -f "%m" "$CSS_FILE" 2>/dev/null || stat -c "%Y" "$CSS_FILE" 2>/dev/null || echo 0)
            
            if [ "$CURRENT_MODIFIED" -gt "$LAST_MODIFIED" ] && [ "$LAST_MODIFIED" -ne 0 ]; then
                update_css
            fi
            
            LAST_MODIFIED=$CURRENT_MODIFIED
        fi
        
        sleep 2
    done
fi
