param(
  [string]$Distro = "Ubuntu",
  [string]$InstallRoot = "$env:LOCALAPPDATA\ResearchPadAgent",
  [switch]$RemoveStartupTask
)

$ErrorActionPreference = "Continue"

function Stop-Port([int]$Port) {
  $processIds = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue |
    Select-Object -ExpandProperty OwningProcess -Unique
  foreach ($processId in $processIds) {
    if ($processId -and $processId -ne $PID) {
      Stop-Process -Id $processId -Force -ErrorAction SilentlyContinue
      Write-Host "Stopped process $processId on port $Port"
    }
  }
}

Stop-Port 8443

& wsl.exe -d $Distro -- bash -lc "pkill -f code-server || true; pkill -f researchpad-agent-extension || true" 2>$null

if ($RemoveStartupTask) {
  Unregister-ScheduledTask -TaskName "ResearchPadAgent" -Confirm:$false -ErrorAction SilentlyContinue
  Write-Host "Removed scheduled task ResearchPadAgent"
}

Write-Host "ResearchPad Agent Windows services stopped."
