#!/bin/bash
# watch_and_update.sh - Auto-regenerate dashboard when demos change
#
# Usage:
#   ./watch_and_update.sh
#
# Watches demo directories and regenerates index.html automatically

echo "🔍 Watching for changes in demo directories..."
echo "Press Ctrl+C to stop"
echo ""

# Function to regenerate
regenerate() {
    echo "📝 Change detected - regenerating dashboard..."
    python3 generate_index.py
    echo "✅ Dashboard updated!"
    echo ""
}

# Initial generation
regenerate

# Watch for changes (requires inotify-tools: sudo apt install inotify-tools)
if command -v inotifywait &> /dev/null; then
    while true; do
        # Watch for new HTML files or changes to existing ones
        inotifywait -q -e create,modify,delete -r \
            threejs_viz/ sdg_viz/ d3_test/ mapbox_test/ claude_code_devtools/ src/ src_infinite/ src_group/ 2>/dev/null || break

        # Regenerate after a short delay to batch changes
        sleep 1
        regenerate
    done
else
    echo "⚠️  inotifywait not found. Install with: sudo apt install inotify-tools"
    echo "Falling back to polling mode (checks every 5 seconds)..."
    echo ""

    # Polling fallback
    last_count=$(find threejs_viz sdg_viz d3_test mapbox_test claude_code_devtools src src_infinite src_group -name "*.html" 2>/dev/null | wc -l)

    while true; do
        sleep 5
        current_count=$(find threejs_viz sdg_viz d3_test mapbox_test claude_code_devtools src src_infinite src_group -name "*.html" 2>/dev/null | wc -l)

        if [ "$current_count" != "$last_count" ]; then
            regenerate
            last_count=$current_count
        fi
    done
fi
