#!/bin/bash
set -e

# Configuration
COMPOSE_FILE="docker-compose.test.yml"
export NATS_ADDR="nats://localhost:4223"
export DATA_PERSISTENCE_SERVICE_URL="http://localhost:3005"
# For services that might need direct DB access (e.g. persistence tests)
export DATABASE_URL="postgresql://postgres:postgres@localhost:5433/fundamental_test"

# Fake Service Host config for providers
export SERVICE_HOST="localhost"
export API_GATEWAY_URL="http://localhost:4000" # Mock

# Keys (Injected for testing)
export ALPHAVANTAGE_API_KEY="PUOO7UPTNXN325NN"
export TUSHARE_API_KEY="f62b415de0a5a947fcb693b66cd299dd6242868bf04ad687800c7f3f"
export FINNHUB_API_KEY="d3fjs5pr01qolkndil0gd3fjs5pr01qolkndil10"
export OPENROUTER_API_KEY="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"
export OPENROUTER_API_URL="https://openrouter.ai/api/v1"
# Common config for services
export SERVER_PORT=0 # Use random/no port for tests to avoid config errors

# Default URLs (From Frontend Defaults)
export ALPHAVANTAGE_MCP_URL="https://mcp.alphavantage.co/mcp"
export TUSHARE_API_URL="http://api.tushare.pro"
export FINNHUB_API_URL="https://finnhub.io/api/v1"
export YFINANCE_API_URL="https://query1.finance.yahoo.com" # Generic default

# Check for MCP URL (now set by default above, but good to keep check if user wants override)
if [ -z "$ALPHAVANTAGE_MCP_URL" ]; then
    echo -e "\033[1;33m[WARNING]\033[0m ALPHAVANTAGE_MCP_URL is not set. Integration tests using it will fail."
    echo "Please set it via: export ALPHAVANTAGE_MCP_URL='...'"
    # Set a dummy for now to prevent crash, but test will fail connection
    export ALPHAVANTAGE_MCP_URL="http://localhost:9999/sse"
fi

function log() {
    echo -e "\033[1;34m[TEST-RUNNER]\033[0m $1"
}

function start_env() {
    log "Starting test infrastructure..."
    docker-compose -f $COMPOSE_FILE up -d --build
    
    log "Waiting for services to be healthy..."
    # Simple wait loop for persistence service
    local max_retries=30
    local count=0
    while ! curl -s http://localhost:3005/health > /dev/null; do
        sleep 2
        count=$((count+1))
        if [ $count -ge $max_retries ]; then
            log "Error: Timeout waiting for persistence service."
            exit 1
        fi
        echo -n "."
    done
    echo ""
    log "Infrastructure is ready!"
}

function stop_env() {
    log "Stopping test infrastructure..."
    docker-compose -f $COMPOSE_FILE down -v
    log "Environment destroyed."
}

function run_tests_in_dir() {
    local dir=$1
    log "Running tests in $dir..."
    if ! (cd "$dir" && cargo test -- --nocapture); then
        log "Tests failed in $dir"
        return 1
    fi
}

function run_tests() {
    local package=$1
    local services_dir="services"

    if [ -n "$package" ]; then
        if [ -d "$services_dir/$package" ]; then
             if ! run_tests_in_dir "$services_dir/$package"; then
                 exit 1
             fi
        else
             log "Error: Package directory '$services_dir/$package' not found."
             exit 1
        fi
    else
        log "Running ALL tests in services/ directory..."
        for dir in "$services_dir"/*; do
            if [ -d "$dir" ] && [ -f "$dir/Cargo.toml" ]; then
                if ! run_tests_in_dir "$dir"; then
                    log "Aborting due to test failure in $dir."
                    exit 1
                fi
            fi
        done
    fi
}

function check_env_ready() {
    if curl -s http://localhost:3005/health > /dev/null; then
        return 0
    else
        return 1
    fi
}

# CLI Argument Parsing
case "$1" in
    "prepare"|"start")
        if check_env_ready; then
             log "Environment is already running."
        else
             start_env
        fi
        ;;
    "destroy"|"stop")
        stop_env
        ;;
    "test")
        # Verify environment is ready
        if ! check_env_ready; then
             log "Error: Test environment is NOT ready."
             log "Please run '$0 prepare' first to start the infrastructure."
             exit 1
        fi
        
        run_tests $2
        ;;
    *)
        echo "Usage: $0 {prepare|destroy|test [package_name]}"
        echo "  prepare (start): Start test infrastructure (Docker)"
        echo "  destroy (stop):  Stop and cleanup test infrastructure"
        echo "  test:            Run cargo test (requires environment to be ready). Optional: provide package name."
        exit 1
        ;;
esac
