param(
    [string]$DockerContext = "test-docker",
    [string]$ComposePath = "core/deploy/docker/1c-agent/compose.yaml",
    [string]$BaseUrl = "http://docker-test.cin.su:8090",
    [string]$ServiceName = "onec-agent",
    [switch]$WithTurnCheck,
    [int]$HealthTimeoutSec = 60,
    [int]$SmokeTimeoutSec = 5,
    [switch]$NoBuild
)

$ErrorActionPreference = "Stop"

function Invoke-CheckedCommand {
    param(
        [string]$Label,
        [string[]]$Command
    )
    Write-Host "[run] $Label"
    $exe = $Command[0]
    $args = $Command[1..($Command.Length - 1)]
    Write-Host ("[cmd] {0} {1}" -f $exe, ($args -join " "))
    & $exe @args
    if ($LASTEXITCODE -ne 0) {
        throw "$Label failed with code=$LASTEXITCODE"
    }
}

try {
    Write-Host "[1] Deploying service '$ServiceName' on context $DockerContext"
    if ($NoBuild) {
        Invoke-CheckedCommand -Label "docker compose up" -Command @(
            "docker", "--context", $DockerContext, "compose", "-f", $ComposePath, "up", "-d", $ServiceName
        )
    } else {
        Invoke-CheckedCommand -Label "docker compose up --build" -Command @(
            "docker", "--context", $DockerContext, "compose", "-f", $ComposePath, "up", "-d", "--build", $ServiceName
        )
    }

    Write-Host "[2] Waiting for health endpoint: $BaseUrl/v1/health"
    $stopAt = (Get-Date).AddSeconds($HealthTimeoutSec)
    do {
        try {
            $response = Invoke-RestMethod -Uri "$BaseUrl/v1/health" -Method Get -TimeoutSec 5
            if ($response.status -eq "ok") {
                Write-Host "[ok] service is healthy"
                break
            }
        } catch {
            Start-Sleep -Milliseconds 1200
        }
    } while ((Get-Date) -lt $stopAt)

    if ((Get-Date) -ge $stopAt) {
        throw "service did not become healthy within ${HealthTimeoutSec}s"
    }

    Write-Host "[3] Running smoke against $BaseUrl"
    $smokeArgs = @("scripts/smoke_onec_agent_api.py", "--base-url", $BaseUrl, "--timeout", $SmokeTimeoutSec.ToString())
    if ($WithTurnCheck) {
        $smokeArgs += "--with-turn-check"
    }
    Invoke-CheckedCommand -Label "smoke_onec_agent_api.py" -Command (@("python") + $smokeArgs)

    Write-Host "[done] onec-agent smoke passed"
    exit 0
} catch {
    Write-Error $_
    exit 1
}
