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

set "HOST=127.0.0.1"
set "PID_FILE=%~dp0server.pid"
set "URL_FILE=%~dp0server.url"

if exist "%PID_FILE%" (
  set /p OLD_PID=<"%PID_FILE%"
  if defined OLD_PID (
    tasklist /FI "PID eq %OLD_PID%" 2>NUL | find "%OLD_PID%" >NUL
    if not errorlevel 1 (
      echo Server is already running. PID: %OLD_PID%
      if exist "%URL_FILE%" (
        set /p URL=<"%URL_FILE%"
      ) else (
        set "URL=http://%HOST%:8080"
      )
      echo URL: !URL!
      start "" "!URL!"
      pause
      exit /b 0
    )
  )
  del "%PID_FILE%" >NUL 2>NUL
)

powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference='Stop';" ^
  "$wd=(Resolve-Path -LiteralPath '%~dp0').Path;" ^
  "$py=Get-Command py -ErrorAction SilentlyContinue;" ^
  "$python=$null;" ^
  "if($py){$python=(& $py.Source -3 -c 'import sys; print(sys.executable)' 2>$null | Select-Object -First 1)};" ^
  "if(-not $python){$cmd=Get-Command python -ErrorAction SilentlyContinue; if($cmd){$python=$cmd.Source}};" ^
  "if(-not $python -or -not (Test-Path -LiteralPath $python)){Write-Host 'Python was not found. Install Python or add it to PATH.'; exit 1};" ^
  "$ports=@(8080,8090,8081,8000,5000,5500,18080,18081,28080,28081,49152,49153,49200);" ^
  "$last='';" ^
  "foreach($port in $ports){" ^
  "  Remove-Item -LiteralPath (Join-Path $wd 'server.out.log') -Force -ErrorAction SilentlyContinue;" ^
  "  Remove-Item -LiteralPath (Join-Path $wd 'server.err.log') -Force -ErrorAction SilentlyContinue;" ^
  "  $args=@('serial_bridge.py','--host','%HOST%','--port',[string]$port);" ^
  "  try{$p=Start-Process -FilePath $python -ArgumentList $args -WorkingDirectory $wd -WindowStyle Hidden -RedirectStandardOutput (Join-Path $wd 'server.out.log') -RedirectStandardError (Join-Path $wd 'server.err.log') -PassThru}catch{$last=$_.Exception.Message; continue};" ^
  "  Start-Sleep -Milliseconds 900;" ^
  "  $p.Refresh();" ^
  "  if(-not $p.HasExited){" ^
  "    $url='http://%HOST%:' + $port;" ^
  "    $p.Id | Set-Content -Encoding ASCII -LiteralPath (Join-Path $wd 'server.pid');" ^
  "    $port | Set-Content -Encoding ASCII -LiteralPath (Join-Path $wd 'server.port');" ^
  "    $url | Set-Content -Encoding ASCII -LiteralPath (Join-Path $wd 'server.url');" ^
  "    Write-Host ('Started server PID: ' + $p.Id);" ^
  "    Write-Host ('URL: ' + $url);" ^
  "    exit 0;" ^
  "  }" ^
  "  if(Test-Path -LiteralPath (Join-Path $wd 'server.err.log')){$last=Get-Content -LiteralPath (Join-Path $wd 'server.err.log') -Raw}" ^
  "}" ^
  "Write-Host 'Server exited immediately on all candidate ports. Check server.err.log.';" ^
  "if($last){Write-Host $last};" ^
  "exit 1;"

if errorlevel 1 (
  echo Failed to start server.
  echo See server.err.log if it was created.
  pause
  exit /b 1
)

if exist "%URL_FILE%" (
  set /p URL=<"%URL_FILE%"
) else (
  set "URL=http://%HOST%:8080"
)

echo Server started.
echo URL: !URL!
echo Logs: server.out.log and server.err.log
start "" "!URL!"
pause
