@echo off
title AgentOrchestrator
cd /d "%~dp0"

echo.
echo  ========================================================
echo        AgentOrchestrator
echo  ========================================================
echo.

REM ── First-run detection ──
if not exist "%~dp0.venv\Scripts\python.exe" (
  echo  [!] First-time setup detected.
  echo      This will install all required components.
  echo      Depending on your internet speed, this takes 5-15 minutes.
  echo.
  echo  Starting installer...
  echo.
  powershell -ExecutionPolicy Bypass -File ".\install_windows.ps1"
  if errorlevel 1 (
    echo.
    echo  [FAIL] Installation failed. Check the output above for details.
    echo         Press any key to close.
    pause >nul
    exit /b %errorlevel%
  )
  echo.
)

if not exist "%~dp0.venv\Scripts\python.exe" (
  echo  [FAIL] Virtual environment was not created. Installation may have failed.
  echo         Press any key to close.
  pause >nul
  exit /b 1
)

REM ── Clean up stale processes ──
echo  [1/3] Checking for existing instances...
powershell -NoProfile -Command "& { $ports = @(8001,8000); foreach ($p in $ports) { try { $c = Get-NetTCPConnection -LocalPort $p -State Listen -ErrorAction Stop | Select-Object -First 1; if ($c) { $proc = Get-Process -Id $c.OwningProcess -ErrorAction SilentlyContinue; if ($proc -and ($proc.ProcessName -match 'python')) { Stop-Process -Id $c.OwningProcess -Force -ErrorAction SilentlyContinue } } } catch {} } }"
if exist "%~dp0.launcher.lock" del /f "%~dp0.launcher.lock" >nul 2>&1

REM ── Start launcher ──
echo  [2/3] Starting server...

if exist "%~dp0.venv\Scripts\pythonw.exe" (
  start "" "%~dp0.venv\Scripts\pythonw.exe" "%~dp0launcher_server.py"
) else (
  start /B "" "%~dp0.venv\Scripts\python.exe" "%~dp0launcher_server.py"
)

REM ── Poll with visible feedback (max ~30 seconds) ──
set TRIES=0
:waitloop
if %TRIES% GEQ 30 goto launcherfailed

REM Show a dot every second for visual progress
<nul set /p =.
powershell -NoProfile -Command "try { $r = Invoke-WebRequest -Uri 'http://127.0.0.1:8001/api/launcher/status' -TimeoutSec 1 -UseBasicParsing -ErrorAction Stop; exit 0 } catch { exit 1 }"
if %errorlevel% EQU 0 goto openbrowser
set /a TRIES+=1
timeout /t 1 /nobreak >nul
goto waitloop

:launcherfailed
echo.
echo.
echo  [FAIL] Server did not start within 30 seconds.
echo.
echo  Possible causes:
echo    - Antivirus blocking the process
echo    - Port 8001 in use by another application
echo    - Missing Python packages (re-run installer)
echo.
if exist "%~dp0launcher_debug.txt" (
  echo  Technical log: %~dp0launcher_debug.txt
)
echo.
echo  Press any key to close.
pause >nul
exit /b 1

:openbrowser
echo.
echo  [3/3] Opening browser...
start "" "http://127.0.0.1:8001"

echo.
echo  ========================================================
echo    AgentOrchestrator is running on http://127.0.0.1:8001
echo  ========================================================
echo.
echo  The browser should open automatically.
echo  You can close this window -- the server keeps running.
echo  To stop: use the Stop button in Settings, or run kill_agent_server.bat
echo.
