@echo off
setlocal EnableExtensions

if /I "%~1"=="__run_hidden__" goto run_hidden

for %%I in ("%~dp0..") do set "PROJECT_DIR=%%~fI"
cd /d "%PROJECT_DIR%"

powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "Start-Process -WindowStyle Hidden -FilePath 'cmd.exe' -ArgumentList '/c ""%~f0"" __run_hidden__'"
exit /b 0

:run_hidden
for %%I in ("%~dp0..") do set "PROJECT_DIR=%%~fI"
cd /d "%PROJECT_DIR%"

call :resolve_base_python
if errorlevel 1 exit /b 1

if not exist ".venv\Scripts\python.exe" (
  %BASE_PYTHON% -m venv .venv
  if errorlevel 1 exit /b 1
)

set "VENV_PY=.venv\Scripts\python.exe"

"%VENV_PY%" -m pip install --disable-pip-version-check -r requirements.txt >nul 2>nul
if errorlevel 1 (
  "%VENV_PY%" -m pip install -r requirements.txt
  if errorlevel 1 exit /b 1
)

for /f "tokens=5" %%P in ('netstat -ano ^| findstr /R /C:":8000 .*LISTENING"') do (
  taskkill /PID %%P /F >nul 2>nul
)

"%VENV_PY%" -m uvicorn local_server.app:app --host 127.0.0.1 --port 8000 --log-level warning
exit /b %errorlevel%

:resolve_base_python
set "BASE_PYTHON="

py -3.11 --version >nul 2>&1
if not errorlevel 1 (
  set "BASE_PYTHON=py -3.11"
  exit /b 0
)

py --version >nul 2>&1
if not errorlevel 1 (
  set "BASE_PYTHON=py"
  exit /b 0
)

python --version >nul 2>&1
if not errorlevel 1 (
  set "BASE_PYTHON=python"
  exit /b 0
)

exit /b 1
