# Project Robustness Validation Script
$ErrorActionPreference = "Continue"
$ProjectRoot = Split-Path -Parent $PSScriptRoot

Set-Location $ProjectRoot

Write-Host "======================================" -ForegroundColor Cyan
Write-Host "  Project Robustness Validation" -ForegroundColor Cyan
Write-Host "======================================" -ForegroundColor Cyan

# 1. Check Go
Write-Host "`n[1] Checking Go..." -ForegroundColor Yellow
$goVersion = go version 2>$null
if ($LASTEXITCODE -eq 0) { Write-Host "OK: $goVersion" -ForegroundColor Green }
else { Write-Host "FAIL: Go not installed" -ForegroundColor Red; exit 1 }

# 2. Check dependencies
Write-Host "`n[2] Checking dependencies..." -ForegroundColor Yellow
go mod tidy 2>$null
if ($LASTEXITCODE -eq 0) { Write-Host "OK: Dependencies OK" -ForegroundColor Green }
else { Write-Host "WARN: Dependencies issue" -ForegroundColor Yellow }

# 3. Static analysis
Write-Host "`n[3] Running vet..." -ForegroundColor Yellow
go vet ./... 2>$null
if ($LASTEXITCODE -eq 0) { Write-Host "OK: No static errors" -ForegroundColor Green }
else { Write-Host "WARN: Static errors found" -ForegroundColor Yellow }

# 4. Build
Write-Host "`n[4] Building..." -ForegroundColor Yellow
if (-not (Test-Path "data")) { New-Item -ItemType Directory -Path "data" -Force | Out-Null }
# Only build main packages, skip docs and e2e (they have special requirements)
go build -o /dev/null ./cmd/server 2>$null
if ($LASTEXITCODE -eq 0) { Write-Host "OK: Build success" -ForegroundColor Green }
else { Write-Host "FAIL: Build failed" -ForegroundColor Red; exit 1 }

# 5. Test
Write-Host "`n[5] Running tests..." -ForegroundColor Yellow
# Skip docs (has swagger generation issues) and e2e (requires special setup)
$packages = go list ./... | Where-Object { $_ -notmatch "/docs$|/e2e$" }
go test -short $packages 2>$null
if ($LASTEXITCODE -eq 0) { Write-Host "OK: Tests passed" -ForegroundColor Green }
else { Write-Host "WARN: Some tests failed" -ForegroundColor Yellow }

# 6. Config check
Write-Host "`n[6] Config file check..." -ForegroundColor Yellow
if (Test-Path "configs/config.yaml") {
    $content = Get-Content "configs/config.yaml" -Raw
    if ($content -match "refresh_token_expire:\s*(\d+)d") {
        Write-Host "FAIL: JWT config uses unsupported 'd' unit" -ForegroundColor Red
        $hours = [int]$matches[1] * 24
        $content = $content -replace "refresh_token_expire:\s*\d+d", "refresh_token_expire: ${hours}h"
        Set-Content "configs/config.yaml" -Value $content -NoNewline
        Write-Host "FIXED: Changed to ${hours}h" -ForegroundColor Green
    } else {
        Write-Host "OK: Config correct" -ForegroundColor Green
    }
} else {
    Write-Host "WARN: Config file missing" -ForegroundColor Yellow
}

Write-Host "`n======================================" -ForegroundColor Cyan
Write-Host "  Validation Complete" -ForegroundColor Cyan
Write-Host "======================================" -ForegroundColor Cyan
