<#
.SYNOPSIS
  Export support diagnostics (versions, health, recent readiness reports).
#>
[CmdletBinding()]
param(
    [string]$SovereignApi = 'http://localhost:3041'
)

$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path $PSScriptRoot -Parent
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$outDir = Join-Path $repoRoot "_readiness\diagnostics-$stamp"
New-Item -ItemType Directory -Path $outDir -Force | Out-Null

if (Test-Path (Join-Path $repoRoot 'VERSION')) {
    Copy-Item (Join-Path $repoRoot 'VERSION') (Join-Path $outDir 'VERSION.txt')
}
node --version | Out-File (Join-Path $outDir 'node-version.txt')
npm --version | Out-File (Join-Path $outDir 'npm-version.txt')

try {
    Invoke-RestMethod -Uri "$SovereignApi/api/health" -TimeoutSec 5 | ConvertTo-Json | Out-File (Join-Path $outDir 'health.json')
} catch {
    $_.Exception.Message | Out-File (Join-Path $outDir 'health-error.txt')
}

try {
    Invoke-RestMethod -Uri "$SovereignApi/api/license" -TimeoutSec 5 | ConvertTo-Json | Out-File (Join-Path $outDir 'license.json')
} catch { }

$zip = Join-Path $repoRoot "_readiness\diagnostics-$stamp.zip"
if (Get-Command Compress-Archive -ErrorAction SilentlyContinue) {
    Compress-Archive -Path "$outDir\*" -DestinationPath $zip -Force
    Write-Host "Diagnostics: $zip"
} else {
    Write-Host "Diagnostics folder: $outDir"
}
