param(
    [switch]$NoBuild,
    [switch]$ActivateServerProfiles
)

$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $PSScriptRoot
$baseCompose = Join-Path $root "infra/docker-compose.yml"
$serverCompose = Join-Path $root "infra/docker-compose.server.yml"
$envFile = Join-Path $root "infra/.env.server"

if (-not (Test-Path -LiteralPath $envFile -PathType Leaf)) {
    throw "Create infra/.env.server from infra/.env.server.example and replace all passwords before deployment."
}

& docker info | Out-Null
if ($LASTEXITCODE -ne 0) { throw "Docker is not available." }

$gpu = Get-Command nvidia-smi -ErrorAction SilentlyContinue
if (-not $gpu) {
    throw "nvidia-smi was not found. Install the NVIDIA driver and NVIDIA Container Toolkit first."
}
& nvidia-smi | Out-Null
if ($LASTEXITCODE -ne 0) { throw "The NVIDIA driver is not ready." }

$registry = Get-Content -Raw -Encoding UTF8 (Join-Path $root "infra/model-registry/server-models.json") | ConvertFrom-Json
foreach ($entry in $registry.models) {
    if ($entry.artifact) {
        New-Item -ItemType Directory -Force -Path (Split-Path -Parent (Join-Path $root "runtime/server-models/$($entry.artifact)")) | Out-Null
    }
}

$arguments = @("compose", "--env-file", $envFile, "-f", $baseCompose, "-f", $serverCompose, "up", "-d")
if (-not $NoBuild) { $arguments += "--build" }
& docker @arguments
if ($LASTEXITCODE -ne 0) { throw "The server stack failed to start." }

$ready = $false
for ($attempt = 1; $attempt -le 60; $attempt++) {
    try {
        $health = Invoke-RestMethod -Uri "http://localhost:8088/actuator/health" -TimeoutSec 5
        if ($health.status -eq "UP") { $ready = $true; break }
    } catch {
        Start-Sleep -Seconds 5
    }
}
if (-not $ready) { throw "The platform did not become healthy within five minutes." }

if ($ActivateServerProfiles) {
    $deploymentIds = @(
        "runtime-vision-detector-gpu",
        "runtime-vision-segmenter-gpu",
        "runtime-thermal-gpu",
        "runtime-change-gpu",
        "runtime-pointcloud-server"
    )
    foreach ($deploymentId in $deploymentIds) {
        $body = @{ force = $false; operator = "server-deployment-script"; reason = "initialize server production profile" } | ConvertTo-Json
        Invoke-RestMethod -Method Post -ContentType "application/json" -Body $body `
            -Uri "http://localhost:8088/api/v1/model-runtime-deployments/$deploymentId/activate" -TimeoutSec 45 | Out-Null
        Write-Host "Activated: $deploymentId"
    }
}

Write-Host "Server stack is ready: http://localhost:8088"
