param(
    [Parameter(Mandatory = $true)][string]$Python,
    [Parameter(Mandatory = $true)][string]$Server
)

$ErrorActionPreference = 'Continue'

# Kill any previous instance of this tool.
try {
    $procs = @(Get-Process pythonw -ErrorAction SilentlyContinue)
    foreach ($p in $procs) {
        try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {}
    }
} catch {}

# Wait briefly for port 8765 to free.
for ($i = 0; $i -lt 10; $i++) {
    $inUse = Get-NetTCPConnection -LocalPort 8765 -State Listen -ErrorAction SilentlyContinue
    if (-not $inUse) { break }
    Start-Sleep -Milliseconds 300
}

if (-not (Test-Path -LiteralPath $Python)) {
    Write-Host "[_run_service] missing python: $Python"
    exit 1
}
if (-not (Test-Path -LiteralPath $Server)) {
    Write-Host "[_run_service] missing server: $Server"
    exit 1
}

# Use System.Diagnostics.Process.Start with CreateNoWindow + no inherited handles.
# Start-Process keeps stdin/stdout handles that may close the child when the parent exits.
try {
    $psi = New-Object System.Diagnostics.ProcessStartInfo
    $psi.FileName = $Python
    $psi.Arguments = '"' + $Server + '"'
    $psi.UseShellExecute = $false
    $psi.CreateNoWindow = $true
    $psi.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
    $psi.RedirectStandardInput = $false
    $psi.RedirectStandardOutput = $false
    $psi.RedirectStandardError = $false
    [void]$psi.EnvironmentVariables.Remove('PYTHONHOME')
    [void]$psi.EnvironmentVariables.Remove('PYTHONPATH')

    $proc = [System.Diagnostics.Process]::Start($psi)
    Write-Host "[_run_service] launched PID $($proc.Id): $Python $Server"
} catch {
    Write-Host "[_run_service] launch failed: $_"
    exit 1
}
exit 0
