param(
    [int]$Port = 56000
)

$killedAny = $false

# Try modern cmdlet first.
$connections = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue
if ($connections) {
    $pids = $connections | Select-Object -ExpandProperty OwningProcess -Unique
    foreach ($procId in $pids) {
        try {
            Stop-Process -Id $procId -Force -ErrorAction Stop
            Write-Host "Stopped process $procId listening on port $Port."
            $killedAny = $true
        }
        catch {
            Write-Warning "Failed to stop process ${procId}: $($_.Exception.Message)"
        }
    }
}

# Fallback for environments where Get-NetTCPConnection is unavailable.
if (-not $killedAny) {
    $netstatLines = netstat -ano | Select-String ":$Port\s"
    $listenLines = $netstatLines | Where-Object { $_.Line -match "LISTENING" }

    $fallbackPids = @()
    foreach ($line in $listenLines) {
        $parts = ($line.Line -replace "\s+", " ").Trim().Split(" ")
        if ($parts.Length -ge 5) {
            $fallbackPids += $parts[-1]
        }
    }

    $fallbackPids = $fallbackPids | Sort-Object -Unique
    foreach ($pidText in $fallbackPids) {
        if ($pidText -match "^\d+$") {
            try {
                Stop-Process -Id ([int]$pidText) -Force -ErrorAction Stop
                Write-Host "Stopped process $pidText listening on port $Port."
                $killedAny = $true
            }
            catch {
                Write-Warning "Failed to stop process ${pidText}: $($_.Exception.Message)"
            }
        }
    }
}

if (-not $killedAny) {
    Write-Host "No listening process found on port $Port."
}
