param(
  [switch]$NoKill
)

$ErrorActionPreference = 'Stop'

function Ensure-Dir($p) {
  if (-not (Test-Path $p)) { New-Item -ItemType Directory -Path $p -Force | Out-Null }
}

function Stop-ListeningPort($port) {
  $lines = netstat -ano | Select-String (":$port ")
  foreach ($l in $lines) {
    $m = [regex]::Match($l.ToString(), "\sLISTENING\s+(\d+)$")
    if ($m.Success) {
      $procId = [int]$m.Groups[1].Value
      try {
        Stop-Process -Id $procId -Force -ErrorAction Stop
        Write-Host "Stopped PID $procId on port $port"
      } catch {
        Write-Host "Failed to stop PID $procId on port $($port): $($_.Exception.Message)"
      }
    }
  }
}

# Repo root is two levels up from this script: server\scripts\*.ps1
$root = Resolve-Path (Join-Path $PSScriptRoot "..\..")
$configPath = Resolve-Path (Join-Path $root "server\config.json")

if (-not $NoKill) {
  Stop-ListeningPort 7201
  Stop-ListeningPort 7301
}

Ensure-Dir (Join-Path $root "server\scripts")

$env:CONFIG_FILE = $configPath.Path

$services = @(
  @{ Name = 'webhook-receiver'; Script = (Join-Path $root 'pages\mall\delivery\webhook-server\webhook-receiver.js'); Out = (Join-Path $root 'webhook-receiver.log'); Err = (Join-Path $root 'webhook-receiver.err.log') },
  @{ Name = 'notify-worker';    Script = (Join-Path $root 'server\notify-worker.js');                          Out = (Join-Path $root 'notify-worker.log');    Err = (Join-Path $root 'notify-worker.err.log') },
  @{ Name = 'push-server';      Script = (Join-Path $root 'server\push-server.js');                            Out = (Join-Path $root 'push-server.log');      Err = (Join-Path $root 'push-server.err.log') }
)

$pids = @{}
foreach ($s in $services) {
  if (-not (Test-Path $s.Script)) { throw "Missing script: $($s.Script)" }
  Write-Host "Starting $($s.Name)..."
  $p = Start-Process -FilePath "node" -ArgumentList @($s.Script) -WorkingDirectory $root.Path -WindowStyle Hidden -RedirectStandardOutput $s.Out -RedirectStandardError $s.Err -PassThru
  $pids[$s.Name] = $p.Id
  Write-Host "  PID=$($p.Id)  out=$($s.Out)  err=$($s.Err)"
}

Ensure-Dir (Join-Path $root 'server\.runtime')
$pidsFile = Join-Path $root 'server\.runtime\delivery-backend.pids.json'
$json = $pids | ConvertTo-Json -Depth 5
[IO.File]::WriteAllText($pidsFile, $json + "`r`n", (New-Object System.Text.UTF8Encoding($false)))
Write-Host "Saved pids: $pidsFile"
Write-Host "Done. Use test sender: node .\pages\mall\delivery\webhook-server\test-send.js"