#!/bin/bash
# Epic 9 串行模式稳定性测试脚本
# 用于对比并行和串行模式的性能差异

RUNS=10
PROJECT_ROOT="/mnt/code/188-179-template-6"
WEB_DIR="${PROJECT_ROOT}/web"
PASSED=0
FAILED=0
TIMES=()

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 "串行模式: 1 worker"
echo "开始时间: $(date)"
echo ""
echo "========================================="
echo ""

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

  # 运行测试（1 worker 串行）- 只运行核心测试文件
  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=1; 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 "🎉 串行模式稳定性验证通过！100% 成功率！"
  exit 0
else
  echo ""
  echo "⚠️  稳定性不足，需要修复失败的测试"
  exit 1
fi
