#!/bin/bash
# 测试服务器API连通性的脚本

echo "=== 测试云盘应用API ==="
echo "目标地址: http://localhost:8080"
echo "=================================="

# 检查服务器是否运行
echo "1. 检查服务器状态..."

# 使用curl测试连接
if curl -s http://localhost:8080/ > /dev/null; then
    echo "✅ 服务器正在运行"
else
    echo "❌ 服务器未运行，请先启动服务器："
    echo "cd /www/wwwroot/云盘后台/backend && python3 server_no_loguru.py"
    exit 1
fi

echo ""
echo "2. 测试API端点..."

# 测试根路径
echo "测试根路径: http://localhost:8080/"
root_response=$(curl -s http://localhost:8000/ 2>/dev/null)
if [ $? -eq 0 ]; then
    echo "✅ 根路径响应正常"
else
    echo "❌ 根路径无响应"
fi

# 测试健康检查
echo "测试健康检查: http://localhost:8080/api/v1/health"
health_response=$(curl -s http://localhost:8080/api/v1/health 2>/dev/null)
if [ $? -eq 0 ]; then
    echo "✅ API健康检查正常"
    echo "响应内容: $health_response"
else
    echo "❌ API健康检查无响应"
fi

# 测试API文档
echo "测试API文档: http://localhost:8080/docs"
docs_response=$(curl -s -I http://localhost:8080/docs 2>/dev/null)
if [ $? -eq 0 ]; then
    echo "✅ API文档可访问"
else
    echo "❌ API文档无法访问"
fi

# 测试测试端点
echo "测试端点: http://localhost:8080/test"
test_response=$(curl -s http://localhost:8080/test 2>/dev/null)
if [ $? -eq 0 ]; then
    echo "✅ 测试端点正常"
    echo "响应内容: $test_response"
else
    echo "❌ 测试端点无响应"
fi

echo ""
echo "3. 详细测试..."

# 详细测试多个端点
endpoints=(
    "http://localhost:8080/"
    "http://localhost:8080/health"
    "http://localhost:8080/api/v1/health"
    "http://localhost:8080/test"
    "http://localhost:8080/openapi.json"
)

success_count=0
total_count=${#endpoints[@]}

for endpoint in "${endpoints[@]}"; do
    echo -n "Testing $endpoint ... "

    response=$(curl -s "$endpoint" 2>/dev/null)
    http_code=$(curl -s -o /dev/null -w "%{http_code}" "$endpoint" 2>/dev/null)

    if [ "$http_code" = "200" ]; then
        echo "✅ (200)"
        success_count=$((success_count + 1))
    else
        echo "❌ ($http_code)"
    fi
done

echo ""
echo "=================================="
echo "测试结果汇总:"
echo "总测试数: $total_count"
echo "成功: $success_count"
echo "失败: $((total_count - success_count))"
echo "成功率: $((success_count * 100 / total_count))%"

if [ $success_count -eq $total_count ]; then
    echo ""
    echo "🎉 所有API测试通过！"
    echo ""
    echo "📋 可访问的URL："
    echo "   http://localhost:8080/ (根路径)"
    echo "   http://localhost:8080/docs (Swagger UI)"
    echo "   http://localhost:8080/redoc (ReDoc)"
    echo "   http://localhost:8080/api/v1/health (健康检查)"
    echo ""
    echo "✅ 服务器在端口8080上运行正常！"
else
    echo ""
    echo "⚠️  有 $((total_count - success_count)) 个测试失败"
    echo "请检查服务器状态和配置"
fi

echo ""
echo "=================================="