# Health check for all running services
$ErrorActionPreference = 'Continue'

$endpoints = @(
    @{ Name = '.NET API   (DYD.Api)';   Url = 'http://localhost:5443/health';                Critical = $true  },
    @{ Name = 'Swagger UI';             Url = 'http://localhost:5443/swagger/v1/swagger.json'; Critical = $false },
    @{ Name = 'Python AI Service';      Url = 'http://localhost:4402/health';                Critical = $false },
    @{ Name = 'Qdrant vector DB';       Url = 'http://localhost:6333/healthz';               Critical = $false },
    @{ Name = 'fe0 (User UI)';          Url = 'http://localhost:8080';                       Critical = $false },
    @{ Name = 'fe-admin (Admin UI)';    Url = 'http://localhost:8082';                       Critical = $false },
    @{ Name = 'Ollama';                 Url = 'http://localhost:11434/api/tags';             Critical = $false }
)

Write-Host ""
Write-Host "Health Check - DYD" -ForegroundColor Cyan
Write-Host ("-" * 70)

$allOk = $true
foreach ($ep in $endpoints) {
    try {
        $r = Invoke-WebRequest -Uri $ep.Url -UseBasicParsing -TimeoutSec 3 -ErrorAction Stop
        if ($r.StatusCode -lt 400) {
            $status = '[UP] '
        }
        else {
            $status = '[DEG]'
        }
        Write-Host ("{0} {1,-30} -> HTTP {2}" -f $status, $ep.Name, $r.StatusCode) -ForegroundColor Green
    }
    catch {
        if ($ep.Critical) {
            $color = 'Red'
            $marker = '[DOWN]'
        }
        else {
            $color = 'DarkYellow'
            $marker = '[OFF] '
        }
        $msg = $_.Exception.Message
        Write-Host ("{0} {1,-30} -> {2}" -f $marker, $ep.Name, $msg) -ForegroundColor $color
        if ($ep.Critical) { $allOk = $false }
    }
}

Write-Host ("-" * 70)
if ($allOk) {
    Write-Host "[OK] All critical services are running." -ForegroundColor Green
    exit 0
}
else {
    Write-Host "[ERROR] Some critical services are down!" -ForegroundColor Red
    exit 1
}
