# Deployment Pre-Flight Checklist (AGENTS.md v16.0)
# Idempotent validation script - safe to run multiple times

param(
    [switch]$Verbose = $false
)

$ErrorActionPreference = "Continue"
$checksPassed = 0
$checksFailed = 0

Write-Host "=== PRE-DEPLOYMENT VALIDATION CHECKLIST ===" -ForegroundColor Green
Write-Host "Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Cyan
Write-Host ""

# Helper function
function Test-Check {
    param([string]$Description, [scriptblock]$Check)
    
    try {
        $result = & $Check
        if ($result) {
            Write-Host "✅ $Description" -ForegroundColor Green
            $script:checksPassed++
            return $true
        } else {
            Write-Host "❌ $Description" -ForegroundColor Red
            $script:checksFailed++
            return $false
        }
    }
    catch {
        Write-Host "❌ $Description (Error: $_)" -ForegroundColor Red
        $script:checksFailed++
        return $false
    }
}

# Tests
Test-Check "1. .NET SDK available" { dotnet --version }
Test-Check "2. PostgreSQL reachable" { (New-Object System.Net.Sockets.TcpClient).ConnectAsync("localhost", 5432).Wait(3000) }
Test-Check "3. Project builds" { dotnet build D:\JobRoomz\KArtSell.Aegis\KArtSell.sln -c Release -v q }
Test-Check "4. Unit tests pass" { dotnet test D:\JobRoomz\KArtSell.Aegis\KArtSell.sln -c Release --filter "Category=UnitTest" -v q }
Test-Check "5. Integration tests pass" { dotnet test D:\JobRoomz\KArtSell.Aegis\KArtSell.sln -c Release --filter "Category=Integration" -v q }
Test-Check "6. Frontend build passes" { Push-Location D:\JobRoomz\KArtSell.Aegis\frontend; pnpm build; Pop-Location }
Test-Check "7. Frontend tests pass" { Push-Location D:\JobRoomz\KArtSell.Aegis\frontend; pnpm test; Pop-Location }
Test-Check "8. No uncommitted changes" { (git -C D:\JobRoomz\KArtSell.Aegis status --porcelain).Count -eq 0 }
Test-Check "9. All 176 tests pass" { (dotnet test D:\JobRoomz\KArtSell.Aegis\KArtSell.sln -c Release --logger "console;verbosity=normal" | Select-String "passed").Count -eq 176 }

Write-Host ""
Write-Host "=== SUMMARY ===" -ForegroundColor Cyan
Write-Host "Passed: $checksPassed" -ForegroundColor Green
Write-Host "Failed: $checksFailed" -ForegroundColor Red
Write-Host ""

if ($checksFailed -eq 0) {
    Write-Host "✅ All pre-deployment checks passed. Ready for deployment." -ForegroundColor Green
    exit 0
} else {
    Write-Host "❌ $checksFailed checks failed. Fix issues before deploying." -ForegroundColor Red
    exit 1
}
