#!/usr/bin/env pwsh
<#
.SYNOPSIS
  Smoke-test telemetry catalog endpoints and dbaopsTelemetryCatalog merge on POST /api/telemetry/snapshot.

.EXAMPLE
  .\scripts\test-telemetry-catalog.ps1

.EXAMPLE
  .\scripts\test-telemetry-catalog.ps1 -BaseUrl http://127.0.0.1:3041 -FullCatalog

.NOTES
  Uses first server from GET /api/fleet. If SOVEREIGN_INGEST_KEY is set on the API, pass the same via -IngestKey or env.
#>
param(
  [string]$BaseUrl = 'http://localhost:3041',
  [string]$IngestKey = $env:SOVEREIGN_INGEST_KEY,
  [switch]$FullCatalog
)

$ErrorActionPreference = 'Stop'
$BaseUrl = $BaseUrl.TrimEnd('/')

function HeadersGet {
  $h = @{ Accept = 'application/json' }
  if ($IngestKey) {
    $h['X-Sovereign-Ingest-Key'] = $IngestKey
  }
  $h
}

function HeadersJsonPost {
  $h = @{ Accept = 'application/json'; 'Content-Type' = 'application/json' }
  if ($IngestKey) {
    $h['X-Sovereign-Ingest-Key'] = $IngestKey
  }
  $h
}

Write-Host "== GET /api/health ==" -ForegroundColor Cyan
$h = Invoke-RestMethod -Uri "$BaseUrl/api/health" -Headers (HeadersGet) -Method Get
Write-Host ($h | ConvertTo-Json -Compress)

Write-Host "`n== GET /api/telemetry/catalog?minimal=1 ==" -ForegroundColor Cyan
$summary = Invoke-RestMethod -Uri "$BaseUrl/api/telemetry/catalog?minimal=1" -Headers (HeadersGet) -Method Get
Write-Host ("sectionCount: {0}" -f $summary.sectionCount)
Write-Host ("version: {0}" -f $summary.version)
if ($summary.sections) {
  $summary.sections | Select-Object number, title, bulletCount | Format-Table -AutoSize
}

if ($FullCatalog) {
  Write-Host "`n== GET /api/telemetry/catalog (full payload, may be large) ==" -ForegroundColor Cyan
  $full = Invoke-RestMethod -Uri "$BaseUrl/api/telemetry/catalog" -Headers (HeadersGet) -Method Get
  Write-Host ("sections: {0}, purpose chars: {1}" -f $full.sectionCount, $full.purpose.Length)
}

Write-Host "`n== GET /api/fleet (first server name) ==" -ForegroundColor Cyan
$fleet = Invoke-RestMethod -Uri "$BaseUrl/api/fleet" -Headers (HeadersGet) -Method Get
$serverName = $fleet[0].ServerName
if (-not $serverName) {
  Write-Host 'No servers in fleet. Register one or use mock/mockData with servers populated.' -ForegroundColor Yellow
  exit 1
}
Write-Host ("Using serverName: {0}" -f $serverName)

$body = @{
  serverName           = $serverName
  cpuPercent           = 12.34
  sqlMemoryUsedMB      = 4096
  activeSessions       = 5
  blockingSessions     = 0
  batchRequestsPerSec  = 400
  avgSignalWaitMs      = 2.5
  dbaopsTelemetryCatalog = @{
    smokeTest           = @{ script = 'test-telemetry-catalog.ps1'; at = (Get-Date).ToUniversalTime().ToString('o') }
    catalogSectionProbe = @{ waitTypesSample = @('CXPACKET', 'WRITELOG', 'PAGEIOLATCH_SH') }
    inventoryStub       = @{ logicalProcessors = 16; virtualization = 'VmwareHypervisorDetected' }
  }
} | ConvertTo-Json -Depth 8

Write-Host "`n== POST /api/telemetry/snapshot (with dbaopsTelemetryCatalog) ==" -ForegroundColor Cyan
$snap = Invoke-RestMethod -Uri "$BaseUrl/api/telemetry/snapshot" -Headers (HeadersJsonPost) `
  -Method Post -Body $body

$id = $snap.snapshot.SnapshotId
Write-Host ("SnapshotId: {0}" -f $id)

$rj = $snap.snapshot.RawMetricsJson
if (-not $rj) {
  Write-Host 'snapshot.RawMetricsJson is null.' -ForegroundColor Yellow
}
else {
  $parsed = $rj | ConvertFrom-Json -ErrorAction SilentlyContinue
  if (-not $parsed) {
    Write-Host 'RawMetricsJson is present but not valid JSON.' -ForegroundColor Yellow
    Write-Host $rj.Substring(0, [Math]::Min(200, $rj.Length))
  }
  elseif ($parsed.dbaops.telemetryDataCollectionCatalog) {
    Write-Host 'rawMetricsJson.dbaops.telemetryDataCollectionCatalog merged OK.' -ForegroundColor Green
    ($parsed.dbaops.telemetryDataCollectionCatalog | ConvertTo-Json -Compress -Depth 4)
  }
  else {
    Write-Host 'JSON parsed but dbaops.telemetryDataCollectionCatalog missing.' -ForegroundColor Yellow
    Write-Host ($parsed | ConvertTo-Json -Compress -Depth 3)
  }
}

Write-Host "`nDone." -ForegroundColor Green
