#!/bin/bash

# SamCloud FileBrowser CSS Live Development
echo "🚀 Starting SamCloud FileBrowser CSS Live Development..."

CSS_DIR="/Volumes/SamMgmt/Containers/SamCloud FileBrowser/src/frontend/src/css"
CONTAINER_NAME="samcloud-filebrowser"

# Function to rebuild and restart container
rebuild_css() {
    echo "📝 CSS changes detected! Rebuilding..."
    
    # Copy CSS to container
    docker exec $CONTAINER_NAME sh -c "mkdir -p /tmp/css-update"
    docker cp "$CSS_DIR/_samcloud.css" "$CONTAINER_NAME:/tmp/css-update/"
    
    # Update the CSS in the container without full rebuild
    docker exec $CONTAINER_NAME sh -c "
        if [ -f /tmp/css-update/_samcloud.css ]; then
            # Find the CSS file location in the built assets
            CSS_FILE=\$(find /usr/local/bin -name '*.css' | head -1)
            if [ -n \"\$CSS_FILE\" ]; then
                cat /tmp/css-update/_samcloud.css >> \$CSS_FILE
                echo '✅ CSS updated in container!'
            else
                echo '❌ Could not find CSS file in container'
            fi
        fi
    "
}

# Watch for CSS changes
echo "👁️  Watching for CSS changes in: $CSS_DIR"
echo "🔄 Edit your CSS files and see changes live!"
echo "🛑 Press Ctrl+C to stop watching"

# Use fswatch if available, otherwise fall back to a simple polling method
if command -v fswatch >/dev/null 2>&1; then
    echo "Using fswatch for file monitoring..."
    fswatch -o "$CSS_DIR" | while read num; do
        rebuild_css
    done
else
    echo "Using polling for file monitoring (install fswatch for better performance)..."
    LAST_MODIFIED=0
    
    while true; do
        CURRENT_MODIFIED=$(stat -f "%m" "$CSS_DIR/_samcloud.css" 2>/dev/null || echo 0)
        
        if [ "$CURRENT_MODIFIED" -gt "$LAST_MODIFIED" ]; then
            LAST_MODIFIED=$CURRENT_MODIFIED
            rebuild_css
        fi
        
        sleep 2
    done
fi
