#!/bin/bash
# 单文件稳定性测试 - 用于调试特定测试文件

if [ -z "$1" ]; then
  echo "用法: $0 <test-file> [runs]"
  echo "示例: $0 disability-person-crud.spec.ts 10"
  echo ""
  echo "可用的测试文件:"
  echo "  - disability-person-photo.spec.ts"
  echo "  - disability-person-bankcard.spec.ts"
  echo "  - disability-person-note.spec.ts"
  echo "  - disability-person-visit.spec.ts"
  echo "  - disability-person-crud.spec.ts"
  exit 1
fi

TEST_FILE="$1"
RUNS="${2:-10}"
PROJECT_ROOT="/mnt/code/188-179-template-6"
WEB_DIR="${PROJECT_ROOT}/web"

cd "${WEB_DIR}" || exit 1

echo "========================================="
echo "单文件稳定性测试"
echo "========================================="
echo "测试文件: ${TEST_FILE}"
echo "运行次数: ${RUNS}"
echo "开始时间: $(date)"
echo "========================================="
echo ""

PASSED=0
FAILED=0
TIMES=()

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

  if pnpm test:e2e:chromium "admin/${TEST_FILE}" --workers=2; 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[@]}")

echo "========================================="
echo "单文件稳定性测试结果"
echo "========================================="
echo "通过: ${PASSED}/${TOTAL} (${PASS_RATE}%)"
echo "失败: ${FAILED}/${TOTAL}"
echo "平均耗时: ${AVG_TIME}s"
echo "========================================="
