#!/bin/bash

# 绑定管理功能测试运行脚本
# 遵循 Tauri 开发规范的测试执行流程

set -e

echo "🧪 开始运行绑定管理功能测试..."

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

# 函数：打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 函数：运行命令并检查结果
run_command() {
    local description=$1
    local command=$2
    
    print_message $BLUE "📋 $description"
    
    if eval $command; then
        print_message $GREEN "✅ $description - 成功"
        return 0
    else
        print_message $RED "❌ $description - 失败"
        return 1
    fi
}

# 检查依赖
print_message $YELLOW "🔍 检查测试环境..."

# 检查 Rust 环境
if ! command -v cargo &> /dev/null; then
    print_message $RED "❌ Cargo 未安装，请先安装 Rust"
    exit 1
fi

# 检查 Node.js 环境
if ! command -v node &> /dev/null; then
    print_message $RED "❌ Node.js 未安装"
    exit 1
fi

# 检查 pnpm
if ! command -v pnpm &> /dev/null; then
    print_message $RED "❌ pnpm 未安装"
    exit 1
fi

print_message $GREEN "✅ 测试环境检查完成"

# 切换到项目目录
cd "$(dirname "$0")/.."

# 运行后端测试
print_message $YELLOW "🦀 运行 Rust 后端测试..."

# 运行项目-模板绑定测试
run_command "项目-模板绑定单元测试" "cargo test project_template_binding_tests --lib"

# 运行素材-模特绑定测试
run_command "素材-模特绑定单元测试" "cargo test material_model_binding_tests --lib"

# 运行集成测试
run_command "绑定管理集成测试" "cargo test integration::binding_management_integration_tests --lib"

# 运行所有后端测试
run_command "所有后端测试" "cargo test --lib"

# 运行前端测试
print_message $YELLOW "⚛️ 运行前端测试..."

# 安装依赖（如果需要）
if [ ! -d "node_modules" ]; then
    run_command "安装前端依赖" "pnpm install"
fi

# 运行前端单元测试
run_command "前端组件测试" "pnpm test:unit"

# 运行前端集成测试
run_command "前端集成测试" "pnpm test:integration"

# 运行所有前端测试
run_command "所有前端测试" "pnpm test"

# 生成测试覆盖率报告
print_message $YELLOW "📊 生成测试覆盖率报告..."

# 后端覆盖率
run_command "后端测试覆盖率" "cargo tarpaulin --out Html --output-dir target/coverage"

# 前端覆盖率
run_command "前端测试覆盖率" "pnpm test:coverage"

# 运行性能测试
print_message $YELLOW "⚡ 运行性能测试..."

# 后端性能测试
run_command "后端性能测试" "cargo bench"

# 前端性能测试
run_command "前端性能测试" "pnpm test:performance"

# 运行端到端测试
print_message $YELLOW "🔄 运行端到端测试..."

# 构建应用
run_command "构建应用" "pnpm tauri build"

# 运行 E2E 测试
run_command "端到端测试" "pnpm test:e2e"

# 测试总结
print_message $GREEN "🎉 所有测试完成！"

# 显示测试结果摘要
echo ""
print_message $BLUE "📈 测试结果摘要："
echo "  - 项目-模板绑定功能: ✅"
echo "  - 素材-模特绑定功能: ✅"
echo "  - 前端组件测试: ✅"
echo "  - 集成测试: ✅"
echo "  - 性能测试: ✅"
echo "  - 端到端测试: ✅"

# 显示覆盖率信息
if [ -f "target/coverage/tarpaulin-report.html" ]; then
    print_message $BLUE "📊 后端覆盖率报告: target/coverage/tarpaulin-report.html"
fi

if [ -f "coverage/index.html" ]; then
    print_message $BLUE "📊 前端覆盖率报告: coverage/index.html"
fi

print_message $GREEN "✨ 绑定管理功能测试全部通过！"
