#!/usr/bin/env bash
set -euo pipefail

echo "======================================="
echo "ARGUS Alert System End-to-End Test"
echo "======================================="
echo ""

# 记录测试开始时间
test_start_time=$(date +%s)

# 函数：等待服务就绪
wait_for_services() {
    echo "[INFO] Waiting for all services to be ready..."
    local max_attempts=${SERVICE_WAIT_ATTEMPTS:-120}
    local attempt=1

    while [ $attempt -le $max_attempts ]; do
        if curl -fs http://localhost:9093/api/v2/status >/dev/null 2>&1; then
            echo "[OK] All services are ready!"
            return 0
        fi
        echo "    Waiting for services... ($attempt/$max_attempts)"
        sleep 5
        ((attempt++))
    done

    echo "[ERROR] Services not ready after $max_attempts attempts"
    return 1
}

# 函数：显示测试步骤
show_step() {
    echo ""
    echo "🔄 Step $1: $2"
    echo "----------------------------------------"
}

# 函数：验证步骤结果
verify_step() {
    if [ $? -eq 0 ]; then
        echo "✅ $1 - SUCCESS"
    else
        echo "❌ $1 - FAILED"
        exit 1
    fi
}

# 开始端到端测试
show_step "1" "Bootstrap - Initialize environment"
./scripts/01_bootstrap.sh
verify_step "Bootstrap"

show_step "2" "Startup - Start all services"
./scripts/02_up.sh
verify_step "Service startup"

# 等待服务完全就绪
wait_for_services || exit 1

# 发送告警数据
show_step "3" "Add alerts - Send test alerts to Alertmanager"
./scripts/03_alertmanager_add_alert.sh
verify_step "Send test alerts"

# 查询告警数据
show_step "4" "Verify data - Query Alertmanager"
./scripts/04_query_alerts.sh
verify_step "Data verification"


# 检查服务健康状态
show_step "Health" "Check service health"
echo "[INFO] Checking service health..."

# 检查 Alertmanager 状态
if curl -fs "http://localhost:9093/api/v2/status" >/dev/null 2>&1; then
    am_status="available"
    echo "✅ Alertmanager status: $am_status"
else
    am_status="unavailable"
    echo "⚠️  Alertmanager status: $am_status"
fi
verify_step "Service health check"

# 清理环境
show_step "5" "Cleanup - Stop all services"
./scripts/05_down.sh
verify_step "Service cleanup"

# 计算总测试时间
test_end_time=$(date +%s)
total_time=$((test_end_time - test_start_time))

echo ""
echo "======================================="
echo "🎉 END-TO-END TEST COMPLETED SUCCESSFULLY!"
echo "======================================="
echo "📊 Test Summary:"
echo "   • Total time: ${total_time}s"
echo "   • Alertmanager status: $am_status"
echo "   • All services started and stopped successfully"
echo ""
echo "✅ The ARGUS Alert system is working correctly!"
echo ""
