#!/bin/bash

# 配置一致性检查脚本
# 用于快速验证系统各组件配置是否一致

echo "🔧 配置一致性检查脚本"
echo "========================"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查结果统计
PASS_COUNT=0
FAIL_COUNT=0

# 检查函数
check_service() {
    local service_name=$1
    local url=$2
    local expected_response=$3
    
    echo -n "检查 $service_name ... "
    
    if command -v curl >/dev/null 2>&1; then
        response=$(curl -s --connect-timeout 5 "$url" 2>/dev/null)
        if [[ $? -eq 0 && "$response" == *"$expected_response"* ]]; then
            echo -e "${GREEN}✅ 通过${NC}"
            ((PASS_COUNT++))
        else
            echo -e "${RED}❌ 失败${NC}"
            echo "   期望包含: $expected_response"
            echo "   实际响应: $response"
            ((FAIL_COUNT++))
        fi
    else
        echo -e "${YELLOW}⚠️  跳过 (curl 未安装)${NC}"
    fi
}

# 检查Docker服务
check_docker_service() {
    local service_name=$1
    echo -n "检查 Docker 服务 $service_name ... "
    
    if command -v docker-compose >/dev/null 2>&1; then
        if docker-compose ps | grep -q "$service_name.*Up"; then
            echo -e "${GREEN}✅ 运行中${NC}"
            ((PASS_COUNT++))
        else
            echo -e "${RED}❌ 未运行${NC}"
            ((FAIL_COUNT++))
        fi
    else
        echo -e "${YELLOW}⚠️  跳过 (docker-compose 未安装)${NC}"
    fi
}

# 检查配置文件
check_config_file() {
    local file_path=$1
    local description=$2
    
    echo -n "检查 $description ... "
    
    if [[ -f "$file_path" ]]; then
        echo -e "${GREEN}✅ 存在${NC}"
        ((PASS_COUNT++))
    else
        echo -e "${RED}❌ 缺失${NC}"
        echo "   文件路径: $file_path"
        ((FAIL_COUNT++))
    fi
}

# 检查端口占用
check_port() {
    local port=$1
    local service_name=$2
    
    echo -n "检查端口 $port ($service_name) ... "
    
    if command -v lsof >/dev/null 2>&1; then
        if lsof -i :$port >/dev/null 2>&1; then
            echo -e "${GREEN}✅ 已占用${NC}"
            ((PASS_COUNT++))
        else
            echo -e "${RED}❌ 未占用${NC}"
            ((FAIL_COUNT++))
        fi
    elif command -v netstat >/dev/null 2>&1; then
        if netstat -an | grep -q ":$port "; then
            echo -e "${GREEN}✅ 已占用${NC}"
            ((PASS_COUNT++))
        else
            echo -e "${RED}❌ 未占用${NC}"
            ((FAIL_COUNT++))
        fi
    else
        echo -e "${YELLOW}⚠️  跳过 (lsof/netstat 未安装)${NC}"
    fi
}

echo "1. 检查基础服务状态"
echo "-------------------"

# 检查Docker服务
check_docker_service "mysql"
check_docker_service "redis"

# 检查端口占用
check_port 3306 "MySQL"
check_port 6379 "Redis"
check_port 8000 "后端API"
check_port 3001 "前端开发服务器"

echo ""
echo "2. 检查服务健康状态"
echo "-------------------"

# 检查后端健康状态
check_service "后端API健康检查" "http://localhost:8000/health" "healthy"

# 检查前端服务
check_service "前端服务" "http://localhost:3001" "考培练系统"

echo ""
echo "3. 检查配置文件"
echo "---------------"

# 检查关键配置文件
check_config_file "kaopeilian-backend/app/config/settings.py" "后端配置文件"
check_config_file "kaopeilian-frontend/src/api/config.ts" "前端API配置"
check_config_file "docker-compose.yml" "Docker配置文件"
check_config_file "配置一致性检查清单.md" "配置检查清单"

echo ""
echo "4. 检查认证功能"
echo "---------------"

# 检查登录API
echo -n "检查登录API ... "
if command -v curl >/dev/null 2>&1; then
    login_response=$(curl -s -X POST http://localhost:8000/api/v1/auth/login \
        -H "Content-Type: application/json" \
        -d '{"username": "testuser", "password": "TestPass123!"}' 2>/dev/null)
    
    if [[ "$login_response" == *"access_token"* ]]; then
        echo -e "${GREEN}✅ 正常工作${NC}"
        ((PASS_COUNT++))
        
        # 提取token测试认证
        if command -v jq >/dev/null 2>&1; then
            token=$(echo "$login_response" | jq -r '.data.access_token' 2>/dev/null)
            if [[ "$token" != "null" && "$token" != "" ]]; then
                echo -n "检查token认证 ... "
                auth_response=$(curl -s -H "Authorization: Bearer $token" \
                    http://localhost:8000/api/v1/auth/me 2>/dev/null)
                
                if [[ "$auth_response" == *"testuser"* ]]; then
                    echo -e "${GREEN}✅ 正常工作${NC}"
                    ((PASS_COUNT++))
                else
                    echo -e "${RED}❌ 失败${NC}"
                    ((FAIL_COUNT++))
                fi
            fi
        else
            echo "   (跳过token测试 - jq未安装)"
        fi
    else
        echo -e "${RED}❌ 失败${NC}"
        echo "   响应: $login_response"
        ((FAIL_COUNT++))
    fi
else
    echo -e "${YELLOW}⚠️  跳过 (curl 未安装)${NC}"
fi

echo ""
echo "5. 检查CORS配置"
echo "---------------"

echo -n "检查CORS预检请求 ... "
if command -v curl >/dev/null 2>&1; then
    cors_response=$(curl -s -X OPTIONS http://localhost:8000/api/v1/auth/login \
        -H "Origin: http://localhost:3001" \
        -H "Access-Control-Request-Method: POST" \
        -H "Access-Control-Request-Headers: Content-Type" 2>/dev/null)
    
    if [[ $? -eq 0 ]]; then
        echo -e "${GREEN}✅ 正常响应${NC}"
        ((PASS_COUNT++))
    else
        echo -e "${RED}❌ 失败${NC}"
        ((FAIL_COUNT++))
    fi
else
    echo -e "${YELLOW}⚠️  跳过 (curl 未安装)${NC}"
fi

echo ""
echo "========================"
echo "📊 检查结果统计"
echo "------------------------"
echo -e "通过: ${GREEN}$PASS_COUNT${NC}"
echo -e "失败: ${RED}$FAIL_COUNT${NC}"

if [[ $FAIL_COUNT -eq 0 ]]; then
    echo -e "\n🎉 ${GREEN}所有检查都通过了！系统配置正常。${NC}"
    exit 0
else
    echo -e "\n⚠️  ${YELLOW}发现 $FAIL_COUNT 个问题，请检查配置。${NC}"
    echo ""
    echo "💡 解决建议:"
    echo "1. 确保Docker服务已启动: docker-compose up -d"
    echo "2. 检查端口是否被占用或服务未启动"
    echo "3. 参考 '配置一致性检查清单.md' 核对配置"
    echo "4. 确保数据库密码、CORS域名等配置一致"
    exit 1
fi
