@echo off
setlocal
cd /d "%~dp0"

set "PID_FILE=%~dp0server.pid"

powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference='Stop';" ^
  "$wd=(Resolve-Path -LiteralPath '%~dp0').Path;" ^
  "$pidPath=Join-Path $wd 'server.pid';" ^
  "if(-not (Test-Path -LiteralPath $pidPath)){Write-Host 'server.pid not found. Server is not running or was not started by start_server.bat.'; exit 0};" ^
  "$text=(Get-Content -LiteralPath $pidPath -Raw).Trim();" ^
  "try{$id=[int]$text}catch{Write-Host 'Invalid PID file.'; Remove-Item -LiteralPath $pidPath -Force -ErrorAction SilentlyContinue; exit 1};" ^
  "$proc=Get-CimInstance Win32_Process -Filter ('ProcessId=' + $id) -ErrorAction SilentlyContinue;" ^
  "if(-not $proc){Write-Host ('Process ' + $id + ' is not running.'); Remove-Item -LiteralPath $pidPath -Force -ErrorAction SilentlyContinue; exit 0};" ^
  "if($proc.CommandLine -notmatch 'serial_bridge\.py'){Write-Host ('PID ' + $id + ' is not serial_bridge.py. Stop cancelled.'); exit 1};" ^
  "Stop-Process -Id $id -Force;" ^
  "Remove-Item -LiteralPath $pidPath -Force -ErrorAction SilentlyContinue;" ^
  "Remove-Item -LiteralPath (Join-Path $wd 'server.port') -Force -ErrorAction SilentlyContinue;" ^
  "Remove-Item -LiteralPath (Join-Path $wd 'server.url') -Force -ErrorAction SilentlyContinue;" ^
  "Write-Host ('Stopped server PID: ' + $id);"

if errorlevel 1 (
  echo Failed to stop server.
  pause
  exit /b 1
)

echo Server stopped.
pause
