#!/bin/bash
# Celery Queue Configuration Validator
# Ensures all configured task queues are included in worker queue lists

set -e

echo "🔍 Validating Celery queue configurations..."

# Extract queues from Celery configuration
CELERY_CONFIG_QUEUES=$(grep -E "\"app\.tasks\." app/celery.py | grep -o '"[^"]*".*queue.*"[^"]*"' | grep -o '"[^"]*"$' | tr -d '"' | sort -u)

echo "📋 Queues configured in app/celery.py:"
echo "$CELERY_CONFIG_QUEUES" | sed 's/^/  - /'

# Check each docker-compose file
for compose_file in docker-compose.dev.yml; do
    if [[ -f "$compose_file" ]]; then
        echo ""
        echo "🔧 Checking $compose_file..."

        # Extract worker command
        WORKER_COMMAND=$(grep -A 1 -B 1 "celery.*worker" "$compose_file" | grep "command:" | head -1)

        if [[ "$WORKER_COMMAND" == *"--queues="* ]]; then
            # Extract queues from command
            WORKER_QUEUES=$(echo "$WORKER_COMMAND" | grep -o -- '--queues=[^[:space:]]*' | cut -d'=' -f2 | tr ',' '\n' | sort)

            echo "📋 Worker queues in $compose_file:"
            echo "$WORKER_QUEUES" | sed 's/^/  - /'

            # Check for missing queues
            MISSING_QUEUES=""
            for queue in $CELERY_CONFIG_QUEUES; do
                if ! echo "$WORKER_QUEUES" | grep -q "^$queue$"; then
                    MISSING_QUEUES="$MISSING_QUEUES $queue"
                fi
            done

            if [[ -n "$MISSING_QUEUES" ]]; then
                echo "❌ Missing queues in $compose_file:$MISSING_QUEUES"
                echo "   Add them to the --queues parameter"
            else
                echo "✅ All queues properly configured in $compose_file"
            fi
        else
            echo "⚠️  No explicit --queues parameter in $compose_file (uses all queues by default)"
        fi
    fi
done

echo ""
echo "🎯 Validation complete!"
