#!/bin/bash

# UAT测试套件运行脚本
# 用途: 执行用户验收测试(User Acceptance Testing)

set -e

echo "========================================="
echo "  Novalon后台管理系统 - UAT测试套件"
echo "========================================="
echo ""

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

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$PROJECT_ROOT"

# 检查Python环境
if ! command -v python3 &> /dev/null; then
    echo -e "${RED}错误: 未找到Python3环境${NC}"
    exit 1
fi

# 检查依赖
echo -e "${YELLOW}检查测试依赖...${NC}"
if ! python3 -c "import pytest" &> /dev/null; then
    echo -e "${YELLOW}正在安装测试依赖...${NC}"
    pip3 install -r requirements.txt
fi

# 解析命令行参数
TEST_TYPE="${1:-all}"
VERBOSE="${2:--v}"

# 测试类型映射
declare -A TEST_PATHS
TEST_PATHS["all"]="tests/uat/"
TEST_PATHS["acceptance"]="tests/uat/test_uat_acceptance.py"
TEST_PATHS["workflow"]="tests/uat/test_uat_workflow.py"
TEST_PATHS["business"]="tests/uat/test_uat_business_scenario.py"
TEST_PATHS["experience"]="tests/uat/test_uat_user_experience.py"

# 显示帮助信息
show_help() {
    echo "用法: $0 [测试类型] [详细级别]"
    echo ""
    echo "测试类型:"
    echo "  all         - 运行所有UAT测试 (默认)"
    echo "  acceptance  - 运行验收测试"
    echo "  workflow    - 运行工作流测试"
    echo "  business    - 运行业务场景测试"
    echo "  experience  - 运行用户体验测试"
    echo ""
    echo "详细级别:"
    echo "  -v          - 详细输出 (默认)"
    echo "  -vv         - 更详细输出"
    echo "  -s          - 显示打印输出"
    echo ""
    echo "示例:"
    echo "  $0 all -v           # 运行所有UAT测试，详细输出"
    echo "  $0 business -vv     # 运行业务场景测试，更详细输出"
    echo "  $0 experience -s    # 运行用户体验测试，显示打印输出"
}

# 检查参数
if [[ "$TEST_TYPE" == "-h" ]] || [[ "$TEST_TYPE" == "--help" ]]; then
    show_help
    exit 0
fi

# 验证测试类型
if [[ ! -v TEST_PATHS[$TEST_TYPE] ]]; then
    echo -e "${RED}错误: 未知的测试类型 '$TEST_TYPE'${NC}"
    echo ""
    show_help
    exit 1
fi

TEST_PATH="${TEST_PATHS[$TEST_TYPE]}"

echo -e "${GREEN}测试类型: $TEST_TYPE${NC}"
echo -e "${GREEN}测试路径: $TEST_PATH${NC}"
echo -e "${GREEN}详细级别: $VERBOSE${NC}"
echo ""

# 设置环境变量
export PYTHONPATH="$PROJECT_ROOT:$PYTHONPATH"

# 运行测试
echo -e "${YELLOW}开始执行UAT测试...${NC}"
echo ""

pytest "$TEST_PATH" \
    "$VERBOSE" \
    --strict-markers \
    --tb=short \
    --cov=. \
    --cov-report=html:htmlcov/uat \
    --cov-report=term-missing \
    --alluredir=allure-results/uat \
    -m "uat" \
    --maxfail=5

# 检查测试结果
TEST_EXIT_CODE=$?

echo ""
echo "========================================="
if [ $TEST_EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}✓ UAT测试全部通过!${NC}"
    echo ""
    echo "测试报告:"
    echo "  - HTML覆盖率报告: htmlcov/uat/index.html"
    echo "  - Allure测试报告: allure-results/uat/"
    echo ""
    echo "查看Allure报告:"
    echo "  allure serve allure-results/uat"
else
    echo -e "${RED}✗ UAT测试失败!${NC}"
    echo ""
    echo "请检查测试日志并修复问题后重新运行。"
fi
echo "========================================="

exit $TEST_EXIT_CODE
