[CmdletBinding()]
param(
    [switch]$NoBuild
)

$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $PSScriptRoot

& "$PSScriptRoot\setup_cpu_models.ps1"

$arguments = @(
    "compose",
    "-f", "$root\infra\docker-compose.yml",
    "-f", "$root\infra\docker-compose.cpu.yml",
    "up", "-d"
)
if (-not $NoBuild) {
    $arguments += "--build"
}

& docker @arguments
if ($LASTEXITCODE -ne 0) {
    throw "Failed to start the Docker Compose CPU stack."
}

Write-Host "Waiting for the platform and AI services..."
$ready = $false
for ($attempt = 0; $attempt -lt 120; $attempt++) {
    Start-Sleep -Seconds 2
    try {
        $backend = Invoke-RestMethod "http://localhost:8080/actuator/health" -TimeoutSec 3
        $vision = Invoke-RestMethod "http://localhost:8101/api/v1/runtime" -TimeoutSec 3
        $spatial = Invoke-RestMethod "http://localhost:8102/api/v1/runtime" -TimeoutSec 3
        if ($backend.status -eq "UP" -and $vision.profile -eq "cpu-local" -and $spatial.profile -eq "cpu-local") {
            $ready = $true
            break
        }
    } catch {
        # Services are still starting.
    }
}

if (-not $ready) {
    docker compose -f "$root\infra\docker-compose.yml" -f "$root\infra\docker-compose.cpu.yml" ps
    throw "The CPU stack did not become ready before the timeout."
}

& "$PSScriptRoot\verify_cpu_runtime.ps1"

Write-Host ""
Write-Host "Rail UAV inspection platform CPU mode is running." -ForegroundColor Green
Write-Host "Platform: http://localhost:8088"
Write-Host "Model runtime status: http://localhost:8088/operations"
Write-Host "Vision runtime: http://localhost:8101/api/v1/runtime"
Write-Host "Spatial runtime: http://localhost:8102/api/v1/runtime"
