#!/bin/bash
set -e

ROOT_DIR=$(pwd)

# Function to cleanup on exit
cleanup() {
    echo "[E2E] Dumping logs for workflow-orchestrator-service..."
    docker logs workflow-orchestrator-service || true
    echo "[E2E] Dumping logs for api-gateway..."
    docker logs api-gateway || true
    echo "[E2E] Dumping logs for report-generator-service..."
    docker logs report-generator-service || true
    echo "[E2E] Dumping logs for tushare-provider-service..."
    docker logs tushare-provider-service || true
    echo "[E2E] Dumping logs for yfinance-provider-service..."
    docker logs yfinance-provider-service || true
    echo "[E2E] Dumping logs for alphavantage-provider-service..."
    docker logs alphavantage-provider-service || true
    echo "[E2E] Dumping logs for finnhub-provider-service..."
    docker logs finnhub-provider-service || true
    
    echo "[E2E] Tearing down environment..."
    cd "$ROOT_DIR"
    docker-compose -f docker-compose.yml -f docker-compose.e2e.yml down
}
# Trap exit to ensure cleanup
trap cleanup EXIT

echo "[E2E] Building and Starting Environment..."
# Build specifically the services we need to ensure latest code
docker-compose -f docker-compose.yml -f docker-compose.e2e.yml up -d --build --remove-orphans

echo "[E2E] Waiting for API Gateway (localhost:4000)..."
MAX_RETRIES=30
count=0
until curl -s http://localhost:4000/health > /dev/null; do
    count=$((count+1))
    if [ $count -ge $MAX_RETRIES ]; then
        echo "Timeout waiting for Gateway"
        exit 1
    fi
    echo "Waiting for Gateway... ($count/$MAX_RETRIES)"
    sleep 2
done
echo "Gateway is ready!"

echo "[E2E] Running Rust Test Runner..."
cd tests/end-to-end
RUST_LOG=info cargo run

echo "[E2E] Tests Completed Successfully!"
