#!/bin/bash
# Vitest 增量执行脚本（在Docker Node容器中运行）
# PR模式下只跑与改动文件相关的测试，大幅节省时间
set -eu

# 如果不是PR事件，直接全量跑
if [ "${GITHUB_EVENT_NAME:-}" != "pull_request" ]; then
  echo "非PR模式，全量执行Vitest"
  bash scripts/ci/step_frontend_run.sh "npx vitest run --coverage"
  exit $?
fi

# 获取PR改动的文件列表
PR_NUMBER=$(echo "${GITHUB_REF:-}" | sed 's|refs/pull/||; s|/.*||')
if [ -z "$PR_NUMBER" ]; then
  echo "无法获取PR编号，全量执行Vitest"
  bash scripts/ci/step_frontend_run.sh "npx vitest run --coverage"
  exit $?
fi

API_URL="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/files?limit=100"
CHANGED_FILES=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" "$API_URL" | python3 -c "
import json, sys
try:
    files = json.load(sys.stdin)
    web_files = []
    for f in files:
        fname = f['filename']
        if fname.startswith('apps/web/src/') and fname.endswith(('.ts', '.tsx', '.js', '.jsx')) and f['status'] != 'removed':
            web_files.append(fname.replace('apps/web/', ''))
    print(' '.join(web_files))
except Exception as e:
    print('')
")

if [ -z "$CHANGED_FILES" ]; then
  echo "PR未改动前端源码文件，跳过Vitest"
  exit 0
fi

FILE_COUNT=$(echo "$CHANGED_FILES" | wc -w)
echo "PR改动了 $FILE_COUNT 个前端文件"

# 如果改动文件太多（超过30个），全量跑更可靠
if [ "$FILE_COUNT" -gt 30 ]; then
  echo "改动文件较多，全量执行Vitest"
  bash scripts/ci/step_frontend_run.sh "npx vitest run --coverage"
  exit $?
fi

echo ""
echo "=== 增量执行 Vitest（只跑相关测试）==="
echo "相关源文件: $CHANGED_FILES"
echo ""

# 在Docker Node容器中执行增量测试
set +e
bash scripts/ci/step_frontend_run.sh "npx vitest run related $CHANGED_FILES"
VITEST_EXIT=$?
set -e

if [ "$VITEST_EXIT" -eq 0 ]; then
  echo ""
  echo "✅ 增量测试通过"
  exit 0
else
  echo ""
  echo "❌ 增量测试失败"
  exit $VITEST_EXIT
fi
