param(
    [string]$BindHost = "0.0.0.0",
    [int]$Port = 8081,
    [switch]$Echo,
    [switch]$NoStdin
)

$listeners = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue
if ($listeners) {
    $pids = $listeners | Select-Object -ExpandProperty OwningProcess -Unique
    Write-Host "Stopping existing listeners on TCP ${Port}: $($pids -join ', ')"
    foreach ($procId in $pids) {
        try {
            Stop-Process -Id $procId -Force -ErrorAction Stop
        }
        catch {
            Write-Warning "Failed to stop process $procId : $_"
        }
    }
    Start-Sleep -Milliseconds 300
}

$args = @("tools/tcp_debug_server.py", "--host", $BindHost, "--port", "$Port")
if ($Echo) {
    $args += "--echo"
}
if ($NoStdin) {
    $args += "--no-stdin"
}

Write-Host "Starting TCP debug server on ${BindHost}:${Port}"
python @args
