@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

REM ========================================
REM 通用测试执行脚本 (Windows 版 - 精简版)
REM 用法: run-tests.bat [browser]
REM 示例: run-tests.bat chrome
REM ========================================

set "BROWSER=%~1"
if "%BROWSER%"=="" set "BROWSER=chrome"

echo 开始执行测试，使用 %BROWSER% 浏览器
echo 使用固定配置运行测试，不依赖环境变量

REM ======================================
REM 浏览器选择和 fallback
REM ======================================
set "FALLBACK_BROWSER=electron"
set "CHROME_CUSTOM=chrome-custom"

if /i "%BROWSER%"=="chrome" (
    echo Replacing chrome with %CHROME_CUSTOM%
    set "BROWSER=%CHROME_CUSTOM%"
)

echo 检查浏览器 %BROWSER% 是否可用...
npx cypress info | findstr /i "%BROWSER%" >nul
if errorlevel 1 (
    echo Browser %BROWSER% not found, falling back to %FALLBACK_BROWSER%
    set "BROWSER=%FALLBACK_BROWSER%"
)

echo Using browser: %BROWSER%
echo ======================================

REM ======================================
REM 确保报告目录存在 & 清理旧的报告
REM ======================================
echo 清理旧的报告文件...
if not exist cypress\reports mkdir cypress\reports
if not exist public\reports mkdir public\reports

del /q /s cypress\reports\*.* 2>nul
del /q /s public\reports\*.* 2>nul

REM ======================================
REM 查找测试文件
REM ======================================
set "SPEC_FILES="
for %%f in (cypress\e2e\*.cy.js) do (
  if not defined SPEC_FILES (
    set "SPEC_FILES=%%f"
  ) else (
    set "SPEC_FILES=!SPEC_FILES!,%%f"
  )
  echo   - %%f
)

REM ======================================
REM 执行测试
REM ======================================
if defined SPEC_FILES (
  echo 执行指定的测试脚本...
  call npx cypress run --browser %BROWSER% --spec "%SPEC_FILES%"
) else (
  echo 未找到第一层测试脚本，执行所有测试...
  call npx cypress run --browser %BROWSER%
)

set "TEST_EXIT_CODE=%ERRORLEVEL%"
echo 测试执行完成，退出码: %TEST_EXIT_CODE%

if %TEST_EXIT_CODE%==0 (
  echo 测试执行成功，生成报告...
) else (
  echo 警告: 测试执行失败（退出码: %TEST_EXIT_CODE%），但仍尝试生成报告...
)

REM ======================================
REM 合并报告 & 生成 HTML
REM ======================================
for /f %%i in ('dir /b /s cypress\reports\*.json 2^>nul ^| find /c /v ""') do set JSON_REPORT_COUNT=%%i
echo 找到 %JSON_REPORT_COUNT% 个JSON报告文件

if %JSON_REPORT_COUNT% gtr 0 (
  echo 合并报告...
  call npx mochawesome-merge cypress\reports\**\*.json -o public\reports\merged-report.json
  if errorlevel 1 (
    echo 报告合并失败
    exit /b 1
  )

  echo 生成HTML报告...
  call npx marge public\reports\merged-report.json --reportDir public\reports --inline
  if errorlevel 1 (
    echo HTML报告生成失败
    exit /b 1
  )

  echo 生成自定义汇总报告...
  call node scripts\generate-summary-report.cjs
  if errorlevel 1 (
    echo 自定义汇总报告生成失败
    exit /b 1
  )

  echo 所有报告生成完成！
  echo 查看汇总报告: public\reports\summary-report.html
  echo 查看详细报告: public\reports\merged-report.html
) else (
  echo 未找到任何JSON报告文件，跳过报告生成
  if not %TEST_EXIT_CODE%==0 (
    echo 测试执行失败，请检查错误信息
    exit /b 1
  )
)

echo 测试执行完成
exit /b 0
