$ErrorActionPreference = "Stop"

if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {
    throw "Docker CLI was not found in PATH. Install Docker Desktop or another Docker engine first."
}

function Test-DockerDaemonReady {
    $null = cmd /c "docker info >nul 2>nul"
    return $LASTEXITCODE -eq 0
}

$dockerReady = Test-DockerDaemonReady

if (-not $dockerReady) {
    Write-Host "Docker daemon is not reachable. Attempting to start Docker Desktop..."
    docker desktop start --detach

    $deadline = (Get-Date).AddMinutes(3)
    do {
        Start-Sleep -Seconds 3
        $dockerReady = Test-DockerDaemonReady
    } while (-not $dockerReady -and (Get-Date) -lt $deadline)

    if (-not $dockerReady) {
        throw "Docker Desktop was started but the daemon did not become ready within 3 minutes."
    }
}

$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
$composeFile = Join-Path $repoRoot "ops/observability/local/docker-compose.yml"

docker compose -f $composeFile up -d

Write-Host "Grafana:    http://localhost:3002"
Write-Host "Prometheus: http://localhost:9090"
Write-Host "Loki:       http://localhost:3100"
Write-Host "Dashboard:  http://localhost:3002/d/athena-auth-local-observability/athena-auth-local-observability"
