# Stop DBAOps Sovereign dev servers (ports 3041 API, 3000 web)
$ErrorActionPreference = "SilentlyContinue"

foreach ($port in @(3041, 3000)) {
  $lines = netstat -ano | Select-String "LISTENING" | Select-String ":$port\s"
  foreach ($line in $lines) {
    $procId = ($line -split '\s+')[-1]
    if ($procId -match '^\d+$' -and $procId -ne '0') {
      Write-Host "Stopping PID $procId on port $port..."
      Stop-Process -Id ([int]$procId) -Force -ErrorAction SilentlyContinue
      if (-not $?) {
        taskkill /PID $procId /F 2>$null
      }
    }
  }
}

# Stop node processes launched from this repo (concurrently / server.js / react-scripts)
$repoRoot = Split-Path $PSScriptRoot -Parent
Get-CimInstance Win32_Process -Filter "Name = 'node.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
  $cmd = [string]$_.CommandLine
  if ($cmd -match [regex]::Escape($repoRoot) -and $cmd -match 'server\.js|react-scripts|concurrently|start:api|start:web') {
    Write-Host "Stopping sovereign node PID $($_.ProcessId)..."
    Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
    if (-not $?) { taskkill /PID $_.ProcessId /F 2>$null }
  }
}

Start-Sleep -Seconds 2
$left = netstat -ano | Select-String "LISTENING" | Select-String ":3041|:3000"
if ($left) {
  Write-Warning "Some listeners remain on 3041/3000."
  Write-Warning "Close the terminal running 'npm start', or end those PIDs in Task Manager, or re-run this script in an elevated PowerShell."
  $left | ForEach-Object { Write-Host "  $_" -ForegroundColor DarkYellow }
} else {
  Write-Host "Ports 3041 and 3000 are free." -ForegroundColor Green
}
