$ErrorActionPreference = "Stop"

$vision = Invoke-RestMethod "http://localhost:8101/api/v1/runtime" -TimeoutSec 10
$spatial = Invoke-RestMethod "http://localhost:8102/api/v1/runtime" -TimeoutSec 10
$platform = (Invoke-RestMethod "http://localhost:8088/api/v1/operations/ai-runtime" -TimeoutSec 10).data

if ($vision.profile -ne "cpu-local" -or $spatial.profile -ne "cpu-local") {
    throw "AI services are not using the cpu-local profile."
}
if ([int]$vision.max_concurrency -ne 1 -or [int]$spatial.max_concurrency -ne 1) {
    throw "CPU mode max concurrency must be 1."
}
if ([int]$vision.max_loaded_models -ne 1 -or [int]$spatial.max_loaded_models -ne 1) {
    throw "CPU mode must keep at most one model loaded."
}
if (-not $spatial.open3d_available) {
    throw "Open3D CPU runtime is unavailable."
}

$models = @($vision.models) + @($spatial.models)
$groups = @($models | Select-Object -ExpandProperty model_group -Unique)
$expected = @("vision-detector", "vision-segmenter", "change-detector", "pointcloud-analyzer", "thermal-analyzer")
if ($models.Count -ne 5) {
    throw "CPU runtime must expose exactly five model groups, received $($models.Count)."
}
foreach ($group in $expected) {
    if ($group -notin $groups) {
        throw "CPU registry is missing model group: $group"
    }
}

if ($platform.vision.profile -ne "cpu-local" -or $platform.spatial.profile -ne "cpu-local") {
    throw "The platform did not aggregate AI runtime status."
}

$sampleRequest = @{
    model_group = "vision-detector"
    model_version = "cpu-v1.0.0"
    resource = @{
        resource_id = "cpu-runtime-check"
        metadata = @{ scene = "tower-crane"; longitude = 116.1; latitude = 39.1 }
    }
    scenes = @("tower-crane")
    parameters = @{ confidence_threshold = 0.55; input_size = 640; precision = "FP32" }
} | ConvertTo-Json -Depth 10
$test = Invoke-RestMethod "http://localhost:8101/api/v1/inference/test" -Method Post -ContentType "application/json" -Body $sampleRequest -TimeoutSec 15
if (-not $test.results -or -not $test.results[0].attributes.execution_mode) {
    throw "Vision inference result has no execution_mode marker."
}

$models | Select-Object model_group, display_name, runtime, artifact_installed, loaded | Format-Table -AutoSize
Write-Host "CPU runtime verification passed. Missing ONNX artifacts are explicitly marked as baseline." -ForegroundColor Green
