# =============================================================================
# 企微IT智能服务台 — 本地开发环境 一键测试脚本
# =============================================================================
# 作用:跑后端 pytest + 前端 vitest(可选)
# 用法:在 PowerShell 中执行
#   .\scripts\dev-test.ps1                # 跑后端 pytest
#   .\scripts\dev-test.ps1 -Frontend      # 也跑前端 vitest
#   .\scripts\dev-test.ps1 -BackendOnly   # 只跑后端
# 前置:docker compose -f docker-compose.dev.yml up -d 已运行
# =============================================================================

param(
    [switch]$Frontend,        # 加这个参数同时跑前端 vitest
    [switch]$BackendOnly,     # 只跑后端
    [switch]$FrontendOnly,    # 只跑前端
    [switch]$SkipBuild,       # 跳过 backend build check
    [switch]$Verbose          # 详细输出
)

$ErrorActionPreference = 'Continue'   # 测试失败不中断,继续跑其他
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectRoot = Split-Path -Parent $ScriptDir
Set-Location $ProjectRoot

Write-Host ""
Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Cyan
Write-Host "  企微IT智能服务台 — 本地测试套件" -ForegroundColor Cyan
Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Cyan
Write-Host "模式:" -ForegroundColor Gray -NoNewline
if ($FrontendOnly) { Write-Host " 仅前端 vitest" -ForegroundColor Magenta }
elseif ($BackendOnly) { Write-Host " 仅后端 pytest" -ForegroundColor Magenta }
elseif ($Frontend) { Write-Host " 后端 pytest + 前端 vitest" -ForegroundColor Magenta }
else { Write-Host " 仅后端 pytest(默认)" -ForegroundColor Magenta }
Write-Host ""

$Script:TotalPassed = 0
$Script:TotalFailed = 0
$Script:TotalError = @()

# ==========================================================================
# 第一步:环境检查
# ==========================================================================
if (-not $FrontendOnly) {
    Write-Host "[1/3] 检查后端依赖..." -ForegroundColor Yellow

    # 检查 backend 目录
    if (-not (Test-Path "backend/pytest.ini")) {
        # 后端可能没 pytest.ini,检查是否有 tests/ 目录
        if (-not (Test-Path "backend/tests")) {
            Write-Host "  ⚠️ backend/tests 目录不存在,跳过 pytest" -ForegroundColor Yellow
            $Script:TotalError += "后端无测试目录"
        }
    }

    # 检查 docker 容器是否在跑
    $BackendStatus = docker ps --filter "name=dev_wecom_backend" --format "{{.Status}}" 2>$null
    if (-not $BackendStatus) {
        Write-Host "  ❌ backend 容器未运行!" -ForegroundColor Red
        Write-Host "     请先执行:.\scripts\dev-start.ps1" -ForegroundColor Gray
        exit 1
    }
    Write-Host "  ✅ backend 容器运行中: $BackendStatus" -ForegroundColor Green
}

# ==========================================================================
# 第二步:跑后端 pytest
# ==========================================================================
if (-not $FrontendOnly) {
    Write-Host ""
    Write-Host "[2/3] 跑后端 pytest..." -ForegroundColor Yellow

    if (Test-Path "backend/tests") {
        $PytestArgs = @("pytest", "-v", "--tb=short", "--color=yes")
        if ($Verbose) { $PytestArgs += "-s" }

        docker exec dev_wecom_backend @PytestArgs

        if ($LASTEXITCODE -eq 0) {
            Write-Host "  ✅ pytest 通过" -ForegroundColor Green
            $Script:TotalPassed++
        } else {
            Write-Host "  ❌ pytest 失败(退出码 $LASTEXITCODE)" -ForegroundColor Red
            $Script:TotalFailed++
            $Script:TotalError += "后端 pytest 失败"
        }
    } else {
        Write-Host "  ⏭️  跳过(无 backend/tests)" -ForegroundColor Yellow
    }
}

# ==========================================================================
# 第三步:跑前端 vitest
# ==========================================================================
if ($Frontend -or $FrontendOnly) {
    Write-Host ""
    Write-Host "[3/3] 跑前端 vitest..." -ForegroundColor Yellow

    $FrontendDirs = @("frontend-h5", "frontend-agent", "frontend-admin", "frontend-portal")
    foreach ($Dir in $FrontendDirs) {
        if (-not (Test-Path "$Dir/node_modules")) {
            Write-Host "  ⏭️  跳过 $Dir (未安装依赖)" -ForegroundColor Yellow
            continue
        }
        if (-not (Test-Path "$Dir/vitest.config.ts") -and -not (Test-Path "$Dir/vitest.config.js")) {
            Write-Host "  ⏭️  跳过 $Dir (无 vitest.config)" -ForegroundColor Yellow
            continue
        }

        Write-Host "  ▶ $Dir" -ForegroundColor Cyan
        Push-Location $Dir
        try {
            if ($Verbose) {
                pnpm test:run 2>&1 | Tee-Object -Variable VitestOutput
            } else {
                pnpm test:run 2>&1 | Out-Null
            }
            if ($LASTEXITCODE -eq 0) {
                Write-Host "    ✅ $Dir 通过" -ForegroundColor Green
                $Script:TotalPassed++
            } else {
                Write-Host "    ❌ $Dir 失败" -ForegroundColor Red
                $Script:TotalFailed++
                $Script:TotalError += "前端 $Dir vitest 失败"
            }
        } finally {
            Pop-Location
        }
    }
} else {
    Write-Host ""
    Write-Host "[3/3] 跳过前端 vitest(加 -Frontend 参数启用)" -ForegroundColor Gray
}

# ==========================================================================
# 总结
# ==========================================================================
Write-Host ""
Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Cyan
Write-Host "  测试结果汇总" -ForegroundColor Cyan
Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Cyan
Write-Host "  通过模块: " -NoNewline -ForegroundColor White
Write-Host $Script:TotalPassed -ForegroundColor Green
Write-Host "  失败模块: " -NoNewline -ForegroundColor White
if ($Script:TotalFailed -eq 0) {
    Write-Host $Script:TotalFailed -ForegroundColor Green
} else {
    Write-Host $Script:TotalFailed -ForegroundColor Red
}
if ($Script:TotalError.Count -gt 0) {
    Write-Host ""
    Write-Host "  失败详情:" -ForegroundColor Yellow
    foreach ($Err in $Script:TotalError) {
        Write-Host "    • $Err" -ForegroundColor Red
    }
}
Write-Host ""

if ($Script:TotalFailed -eq 0) {
    Write-Host "🎉 全部测试通过!" -ForegroundColor Green
    exit 0
} else {
    Write-Host "⚠️ 有测试失败,请查看上方输出" -ForegroundColor Yellow
    exit 1
}
