$ErrorActionPreference = "Stop"
$ProjectRoot = Split-Path -Parent $PSScriptRoot
$BackendRoot = Join-Path $ProjectRoot "backend"

if (-not (Test-Path -LiteralPath (Join-Path $BackendRoot ".env"))) {
    throw "缺少 backend/.env。请先创建该文件并配置后端环境变量。"
}

$Uv = Get-Command uv -ErrorAction SilentlyContinue
if ($null -eq $Uv) {
    throw "未找到 uv。"
}

Push-Location $ProjectRoot
try {
    uv run --project backend python -c "import sys; assert sys.version_info[:2] == (3, 12); print(sys.version)"
    if ($LASTEXITCODE -ne 0) {
        throw "Python 3.12 环境检查失败。"
    }
}
finally {
    Pop-Location
}

$MySql = Test-NetConnection -ComputerName 127.0.0.1 -Port 3306 -WarningAction SilentlyContinue
if (-not $MySql.TcpTestSucceeded) {
    throw "MySQL 127.0.0.1:3306 未监听。"
}

$Redis = Test-NetConnection -ComputerName 127.0.0.1 -Port 6379 -WarningAction SilentlyContinue
if (-not $Redis.TcpTestSucceeded) {
    throw "Redis 127.0.0.1:6379 未监听。"
}

Write-Host "环境检查通过：uv、Python 3.12、MySQL、Redis。"
