#!/bin/bash
# Epic 9 稳定性测试脚本
# 运行残疾人管理核心测试 10 次，验证稳定性
# 测试范围：37个核心测试（photo、bankcard、note、visit、crud）

# 配置
set +e  # 不在错误时立即退出，确保完成所有 10 次运行
RUNS=10
PROJECT_ROOT="/mnt/code/188-179-template-6"
WEB_DIR="${PROJECT_ROOT}/web"
PASSED=0
FAILED=0
TIMES=()

# 切换到 web 目录
cd "${WEB_DIR}" || exit 1

echo "========================================="
echo "Epic 9 稳定性验证测试"
echo "========================================="
echo "运行次数: ${RUNS}"
echo "测试范围: 残疾人管理核心测试 (37 个测试)"
echo "  - disability-person-photo.spec.ts (8 测试)"
echo "  - disability-person-bankcard.spec.ts (8 测试)"
echo "  - disability-person-note.spec.ts (8 测试)"
echo "  - disability-person-visit.spec.ts (10 测试)"
echo "  - disability-person-crud.spec.ts (16 测试)"
echo "并行模式: 4 workers"
echo "开始时间: $(date)"
echo ""
echo "========================================="
echo ""

# 运行测试
for i in $(seq 1 ${RUNS}); do
  echo "=== 运行 #${i}/${RUNS} ==="
  START=$(date +%s)

  # 运行测试（4 workers 并行）- 只运行核心测试文件
  if pnpm test:e2e:chromium admin/disability-person-photo.spec.ts admin/disability-person-bankcard.spec.ts admin/disability-person-note.spec.ts admin/disability-person-visit.spec.ts admin/disability-person-crud.spec.ts --workers=4; then
    PASSED=$((PASSED + 1))
    echo "✅ 运行 #${i} 通过"
  else
    FAILED=$((FAILED + 1))
    echo "❌ 运行 #${i} 失败"
  fi

  END=$(date +%s)
  DURATION=$((END - START))
  TIMES+=($DURATION)
  echo "⏱️  耗时: ${DURATION}s"
  echo ""
done

# 计算统计数据
TOTAL=$((PASSED + FAILED))
PASS_RATE=$((PASSED * 100 / TOTAL))
AVG_TIME=$(awk '{sum+=$1} END {print sum/NR}' <<< "${TIMES[@]}")
MIN_TIME=$(printf "%s\n" "${TIMES[@]}" | sort -n | head -1)
MAX_TIME=$(printf "%s\n" "${TIMES[@]}" | sort -n | tail -1)

# 输出结果
echo "========================================="
echo "稳定性测试结果"
echo "========================================="
echo "通过: ${PASSED}/${TOTAL} (${PASS_RATE}%)"
echo "失败: ${FAILED}/${TOTAL}"
echo ""
echo "执行时间统计:"
echo "  平均: ${AVG_TIME}s"
echo "  最快: ${MIN_TIME}s"
echo "  最慢: ${MAX_TIME}s"
echo ""
echo "结束时间: $(date)"
echo "========================================="

# 判断结果
if [ $PASSED -eq $TOTAL ]; then
  echo ""
  echo "🎉 Epic 9 稳定性验证通过！100% 成功率！"
  echo "✅ Epic 9 可以标记为完成"
  exit 0
else
  echo ""
  echo "⚠️  稳定性不足，需要修复失败的测试"
  echo "❌ 请分析失败原因并修复后重新运行"
  exit 1
fi
