@echo off
setlocal

set "AGENT_ROOT=%~dp0"

powershell -NoProfile -ExecutionPolicy Bypass -Command ^
 "$ErrorActionPreference = 'Stop';" ^
 "$root = [System.IO.Path]::GetFullPath($env:AGENT_ROOT);" ^
 "$normalizedRoot = $root.TrimEnd('\').ToLowerInvariant();" ^
 "$venvPython = [System.IO.Path]::GetFullPath((Join-Path $root '.venv\Scripts\python.exe')).ToLowerInvariant();" ^
 "$venvPythonw = [System.IO.Path]::GetFullPath((Join-Path $root '.venv\Scripts\pythonw.exe')).ToLowerInvariant();" ^
 "$killed = 0;" ^
 "$stopped = New-Object 'System.Collections.Generic.HashSet[int]';" ^
 "function Stop-AgentPid([int]$ProcessId, [string]$Reason) { if ($ProcessId -le 0) { return }; if (-not $stopped.Add($ProcessId)) { return }; try { Stop-Process -Id $ProcessId -Force -ErrorAction Stop; $script:killed++; Write-Host ('[AgentOrchestrator] Stopped PID ' + $ProcessId + ' (' + $Reason + ')') -ForegroundColor Cyan } catch {} }" ^
 "function Stop-AgentListener([int]$Port, [string[]]$Needles) { if (-not (Get-Command Get-NetTCPConnection -ErrorAction SilentlyContinue)) { return }; try { $listeners = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction Stop } catch { return }; foreach ($listener in $listeners) { $proc = Get-CimInstance Win32_Process -Filter ('ProcessId = ' + $listener.OwningProcess) -ErrorAction SilentlyContinue; if (-not $proc) { continue }; $name = ([string]$proc.Name).ToLowerInvariant(); if ($name -ne 'python.exe' -and $name -ne 'pythonw.exe') { continue }; $cmd = [string]$proc.CommandLine; if ([string]::IsNullOrWhiteSpace($cmd)) { continue }; $cmdLower = $cmd.ToLowerInvariant(); $matches = $false; foreach ($needle in $Needles) { if ($cmdLower.Contains($needle.ToLowerInvariant())) { $matches = $true; break } }; if ($matches) { Stop-AgentPid -ProcessId $listener.OwningProcess -Reason ('listener on port ' + $Port) } } }" ^
 "$py = Get-CimInstance Win32_Process -Filter \"Name='python.exe' OR Name='pythonw.exe'\" -ErrorAction SilentlyContinue;" ^
 "foreach ($proc in $py) { $cmd = [string]$proc.CommandLine; $exe = [string]$proc.ExecutablePath; $cmdLower = $cmd.ToLowerInvariant(); $exeLower = $exe.ToLowerInvariant(); $matchesRoot = (-not [string]::IsNullOrWhiteSpace($cmd) -and $cmdLower.Contains($normalizedRoot)); $matchesVenv = (-not [string]::IsNullOrWhiteSpace($exe) -and ($exeLower -eq $venvPython -or $exeLower -eq $venvPythonw)); if ($matchesRoot -or $matchesVenv) { Stop-AgentPid -ProcessId $proc.ProcessId -Reason 'repo or venv match' } }" ^
 "Stop-AgentListener -Port 8001 -Needles @('launcher_server.py');" ^
 "Stop-AgentListener -Port 8000 -Needles @('backend.main:app', '-m uvicorn');" ^
 "$lockFile = Join-Path $root '.launcher.lock';" ^
 "if (Test-Path $lockFile) { try { Remove-Item -Path $lockFile -Force -ErrorAction Stop; Write-Host '[AgentOrchestrator] Removed stale .launcher.lock' -ForegroundColor Cyan } catch {} }" ^
 "if ($killed -gt 0) { Write-Host ('[AgentOrchestrator] Server reset complete: stopped ' + $killed + ' process(es).') -ForegroundColor Green } else { Write-Host '[AgentOrchestrator] No running AgentOrchestrator process found.' -ForegroundColor Yellow }"

if errorlevel 1 (
  echo [AgentOrchestrator] Failed to stop the server cleanly.
  exit /b 1
)

echo [AgentOrchestrator] Klaar.
endlocal