#!/bin/bash

# Define the services to check (order matters for dependencies)
SERVICES=(
    "services/common-contracts"
    "services/data-persistence-service"
    "services/workflow-orchestrator-service"
    "services/api-gateway"
    "services/report-generator-service"
    "services/alphavantage-provider-service"
    "services/tushare-provider-service"
    "services/finnhub-provider-service"
    "services/yfinance-provider-service"
)

echo "========================================================"
echo "       RUST SERVICES COMPILATION CHECK SEQUENCE         "
echo "========================================================"
echo ""

FAIL_COUNT=0
FAILED_SERVICES=()

for service_path in "${SERVICES[@]}"; do
    echo "--------------------------------------------------------"
    echo ">>> CHECKING: $service_path"
    echo "--------------------------------------------------------"
    
    if [ -d "$service_path" ]; then
        pushd "$service_path" > /dev/null
        
        # Run cargo check with SQLX_OFFLINE=true
        if SQLX_OFFLINE=true cargo check --tests --all-features; then
            echo "✅ SUCCESS: $service_path compiled successfully."
        else
            echo "❌ FAILURE: $service_path failed to compile."
            FAIL_COUNT=$((FAIL_COUNT+1))
            FAILED_SERVICES+=("$service_path")
        fi
        
        popd > /dev/null
    else
        echo "⚠️ WARNING: Directory $service_path not found!"
    fi
    echo ""
done

echo "========================================================"
echo "                 CHECK COMPLETE                         "
echo "========================================================"

if [ $FAIL_COUNT -eq 0 ]; then
    echo "🎉 All services passed cargo check!"
    exit 0
else
    echo "💥 $FAIL_COUNT services failed to compile:"
    for failed in "${FAILED_SERVICES[@]}"; do
        echo "  - $failed"
    done
    echo ""
    echo "Please review errors above."
    exit 1
fi
