#!/bin/bash
# 健康检查脚本 - 检查所有依赖服务是否正常

echo "🏥 开始健康检查..."
echo ""

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 检查计数
PASS=0
FAIL=0
FAILED_SERVICES=()

# 检查函数
check_service() {
    local service_name=$1
    local check_command=$2
    local fix_command=$3

    echo -n "Checking $service_name ... "

    if eval "$check_command" > /dev/null 2>&1; then
        echo -e "${GREEN}✓ OK${NC}"
        PASS=$((PASS + 1))
    else
        echo -e "${RED}✗ FAIL${NC}"
        FAIL=$((FAIL + 1))
        FAILED_SERVICES+=("$service_name:$fix_command")
    fi
}

# 检查 PostgreSQL
echo -e "${YELLOW}=== 数据库服务 ===${NC}"
check_service "PostgreSQL" "pg_isready -h localhost -p 5432" "sudo systemctl start postgresql"

# 检查 Redis (支持 Docker 和本地)
echo -e "${YELLOW}=== 缓存服务 ===${NC}"
if command -v redis-cli &> /dev/null; then
    check_service "Redis" "redis-cli -h localhost -p 6379 ping" "docker start blockchain-service-redis-1 或 redis-server --daemonize yes"
elif command -v docker &> /dev/null; then
    check_service "Redis" "docker exec blockchain-service-redis-1 redis-cli ping" "docker start blockchain-service-redis-1"
else
    check_service "Redis" "nc -zv localhost 6379" "docker start blockchain-service-redis-1"
fi

# 检查 Kafka
echo -e "${YELLOW}=== 消息队列服务 ===${NC}"
check_service "Kafka" "nc -zv localhost 9092" "启动 Kafka (需要手动启动)"

# 检查区块链 RPC
echo -e "${YELLOW}=== 区块链 RPC ===${NC}"
check_service "KAVA RPC" "curl -sf https://evm.kava.io -X POST -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'" "检查网络连接或 RPC 端点"
check_service "BSC RPC" "curl -sf https://bsc-dataseed.binance.org -X POST -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'" "检查网络连接或 RPC 端点"

# 检查应用服务
echo -e "${YELLOW}=== 应用服务 ===${NC}"
check_service "Blockchain Service" "curl -f http://localhost:3012/health" "npm run start:dev"

# 检查 Swagger 文档
echo -e "${YELLOW}=== API 文档 ===${NC}"
check_service "Swagger UI" "curl -f http://localhost:3012/api" "等待 Blockchain Service 启动"

echo ""
echo -e "${YELLOW}======================================${NC}"
echo -e "${YELLOW}健康检查完成！${NC}"
echo -e "${GREEN}正常: $PASS${NC}"
echo -e "${RED}异常: $FAIL${NC}"
echo -e "${YELLOW}======================================${NC}"

if [ $FAIL -eq 0 ]; then
    echo -e "${GREEN}✓ 所有服务正常！${NC}"
    echo ""
    echo -e "${BLUE}现在可以运行测试：${NC}"
    echo "  ./scripts/quick-test.sh"
    exit 0
else
    echo -e "${RED}✗ 存在异常的服务！${NC}"
    echo ""
    echo -e "${BLUE}修复建议：${NC}"
    for service_info in "${FAILED_SERVICES[@]}"; do
        service_name="${service_info%%:*}"
        fix_command="${service_info#*:}"
        echo -e "${YELLOW}  • $service_name:${NC} $fix_command"
    done
    echo ""
    echo -e "${BLUE}或者运行一键启动脚本：${NC}"
    echo "  ./scripts/start-all.sh"
    exit 1
fi
