$ErrorActionPreference = "Stop"

$root = Split-Path -Parent $MyInvocation.MyCommand.Path
$pidFile = Join-Path $root ".orchestration\\pids.json"

if (Test-Path $pidFile) {
  $pids = Get-Content $pidFile | ConvertFrom-Json
  foreach ($name in @("frontend", "engine", "backend")) {
    $pid = $pids.$name
    if ($pid) {
      $proc = Get-Process -Id $pid -ErrorAction SilentlyContinue
      if ($proc) {
        Write-Host "Stopping $name (pid $pid)..."
        Stop-Process -Id $pid
      }
    }
  }
  Remove-Item $pidFile -Force
} else {
  Write-Host "No pid file found."
}

Write-Host "Stopping PostgreSQL (docker)..."
try {
  docker compose stop postgres | Out-Null
} catch {
  Write-Host "Docker not available or postgres not running."
}
