#!/bin/bash

# 全自动MCP语音服务测试脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_test() {
    echo -e "${PURPLE}[TEST]${NC} $1"
}

# 服务配置
SERVICE_URL="http://localhost:9020"
MCP_ENDPOINT="$SERVICE_URL/mcp"
STATUS_ENDPOINT="$SERVICE_URL/auto-status"
HEALTH_ENDPOINT="$SERVICE_URL/health"

# 测试计数器
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# 测试函数
run_test() {
    local test_name="$1"
    local test_command="$2"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    log_test "测试 $TOTAL_TESTS: $test_name"
    
    if eval "$test_command"; then
        PASSED_TESTS=$((PASSED_TESTS + 1))
        log_success "✅ $test_name - 通过"
    else
        FAILED_TESTS=$((FAILED_TESTS + 1))
        log_error "❌ $test_name - 失败"
    fi
    echo ""
}

# 检查服务状态
check_service_health() {
    curl -s "$HEALTH_ENDPOINT" > /dev/null 2>&1
}

# 检查全自动MCP状态
check_auto_mcp_status() {
    local response=$(curl -s "$STATUS_ENDPOINT")
    echo "$response" | grep -q '"success": true'
}

# 测试智能语音生成
test_smart_voice_generate() {
    local payload='{
        "tool": "smart_voice_generate",
        "args": {
            "text": "Hello world! 你好世界！这是一个测试。",
            "speaker": "auto",
            "language": "auto",
            "emotion": "auto",
            "quality": "standard"
        }
    }'
    
    local response=$(curl -s -X POST "$MCP_ENDPOINT" \
        -H "Content-Type: application/json" \
        -d "$payload")
    
    echo "$response" | grep -q "智能语音生成成功"
}

# 测试批量语音处理
test_batch_voice_process() {
    local payload='{
        "tool": "batch_voice_process",
        "args": {
            "texts": ["测试文本1", "Test text 2", "テストテキスト3"],
            "speaker": "default",
            "language": "zh-cn",
            "emotion": "neutral",
            "parallel": false
        }
    }'
    
    local response=$(curl -s -X POST "$MCP_ENDPOINT" \
        -H "Content-Type: application/json" \
        -d "$payload")
    
    echo "$response" | grep -q "批量语音处理完成"
}

# 测试多语言合成
test_multi_language_synthesis() {
    local payload='{
        "tool": "multi_language_synthesis",
        "args": {
            "text_segments": [
                {"text": "Hello", "language": "en"},
                {"text": "你好", "language": "zh-cn"},
                {"text": "こんにちは", "language": "ja"}
            ],
            "speaker": "default",
            "emotion": "neutral"
        }
    }'
    
    local response=$(curl -s -X POST "$MCP_ENDPOINT" \
        -H "Content-Type: application/json" \
        -d "$payload")
    
    echo "$response" | grep -q "多语言合成完成"
}

# 测试系统状态查询
test_system_status() {
    local payload='{
        "tool": "auto_voice_system_status",
        "args": {}
    }'
    
    local response=$(curl -s -X POST "$MCP_ENDPOINT" \
        -H "Content-Type: application/json" \
        -d "$payload")
    
    echo "$response" | grep -q "全自动语音系统状态报告"
}

# 测试语音风格分析（使用模拟数据）
test_voice_style_analysis() {
    # 创建一个简单的Base64音频数据（模拟）
    local fake_audio="UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA="
    
    local payload='{
        "tool": "voice_style_analysis",
        "args": {
            "audio_base64": "'$fake_audio'"
        }
    }'
    
    local response=$(curl -s -X POST "$MCP_ENDPOINT" \
        -H "Content-Type: application/json" \
        -d "$payload")
    
    # 由于是模拟数据，可能会失败，但我们检查是否有响应
    echo "$response" | grep -q "语音风格分析"
}

# 测试语音质量增强
test_voice_quality_enhance() {
    # 使用模拟音频数据
    local fake_audio="UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA="
    
    local payload='{
        "tool": "voice_quality_enhance",
        "args": {
            "audio_base64": "'$fake_audio'",
            "enhancement_level": "standard"
        }
    }'
    
    local response=$(curl -s -X POST "$MCP_ENDPOINT" \
        -H "Content-Type: application/json" \
        -d "$payload")
    
    # 检查是否有响应
    echo "$response" | grep -q "语音质量增强"
}

# 性能测试
performance_test() {
    log_info "开始性能测试..."
    
    local start_time=$(date +%s)
    
    # 连续调用智能语音生成
    for i in {1..3}; do
        log_info "性能测试 $i/3"
        test_smart_voice_generate > /dev/null 2>&1
    done
    
    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    
    log_success "性能测试完成，耗时: ${duration}秒"
}

# 显示测试结果
show_test_results() {
    echo ""
    echo "=================================="
    echo -e "${CYAN}🧪 全自动MCP语音服务测试报告${NC}"
    echo "=================================="
    echo ""
    echo -e "📊 测试统计:"
    echo -e "  • 总测试数: ${TOTAL_TESTS}"
    echo -e "  • 通过测试: ${GREEN}${PASSED_TESTS}${NC}"
    echo -e "  • 失败测试: ${RED}${FAILED_TESTS}${NC}"
    echo -e "  • 成功率: $(( PASSED_TESTS * 100 / TOTAL_TESTS ))%"
    echo ""
    
    if [ $FAILED_TESTS -eq 0 ]; then
        echo -e "${GREEN}🎉 所有测试通过！全自动MCP语音服务运行正常${NC}"
    else
        echo -e "${YELLOW}⚠️  有 $FAILED_TESTS 个测试失败，请检查服务状态${NC}"
    fi
    
    echo ""
    echo "=================================="
}

# 主函数
main() {
    echo -e "${PURPLE}🎤 全自动MCP语音服务测试套件${NC}"
    echo ""
    
    # 检查服务是否运行
    log_info "检查服务状态..."
    if ! curl -s "$HEALTH_ENDPOINT" > /dev/null 2>&1; then
        log_error "服务未运行，请先启动服务: ./start-voice-clone-mcp.sh"
        exit 1
    fi
    log_success "服务运行正常"
    echo ""
    
    # 运行测试
    log_info "开始运行全自动MCP功能测试..."
    echo ""
    
    # 基础功能测试
    run_test "服务健康检查" "check_service_health"
    run_test "全自动MCP状态检查" "check_auto_mcp_status"
    
    # 核心功能测试
    run_test "智能语音生成" "test_smart_voice_generate"
    run_test "批量语音处理" "test_batch_voice_process"
    run_test "多语言合成" "test_multi_language_synthesis"
    run_test "系统状态查询" "test_system_status"
    
    # 高级功能测试（可能因为模拟数据而失败）
    run_test "语音风格分析" "test_voice_style_analysis"
    run_test "语音质量增强" "test_voice_quality_enhance"
    
    # 性能测试
    performance_test
    
    # 显示结果
    show_test_results
    
    # 显示服务信息
    echo ""
    log_info "📋 服务信息:"
    echo "  • 服务地址: $SERVICE_URL"
    echo "  • MCP端点: $MCP_ENDPOINT"
    echo "  • 状态端点: $STATUS_ENDPOINT"
    echo "  • API文档: $SERVICE_URL/docs"
    echo ""
    
    log_info "🔧 可用工具:"
    echo "  • smart_voice_generate - 智能语音生成"
    echo "  • voice_clone_with_reference - 参考音频克隆"
    echo "  • batch_voice_process - 批量语音处理"
    echo "  • voice_style_analysis - 语音风格分析"
    echo "  • voice_quality_enhance - 语音质量增强"
    echo "  • multi_language_synthesis - 多语言合成"
    echo "  • auto_voice_system_status - 系统状态查询"
    echo ""
}

# 运行主函数
main "$@"