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

rem Keep the virtual environment outside the deeply nested project directory.
rem This prevents Windows Error 206 during NumPy/SciPy installation.
set "GBI_ENV_ROOT=%LOCALAPPDATA%\UNNS\GBI010"
set "GBI_PY=%GBI_ENV_ROOT%\Scripts\python.exe"

set "PYLAUNCHER=python"
where py >nul 2>nul && set "PYLAUNCHER=py -3"

if not exist "%GBI_PY%" (
  echo Creating short-path Python environment:
  echo   %GBI_ENV_ROOT%
  if not exist "%LOCALAPPDATA%\UNNS" mkdir "%LOCALAPPDATA%\UNNS"
  %PYLAUNCHER% -m venv "%GBI_ENV_ROOT%" || goto :error
)

if exist ".venv" (
  echo Note: the incomplete local .venv is ignored. It may be deleted manually.
)

"%GBI_PY%" -c "import fastapi,uvicorn,sklearn,pandas,numpy,matplotlib,multipart" >nul 2>nul
if errorlevel 1 (
  echo Installing chamber requirements into the short-path environment...
  "%GBI_PY%" -m pip install --upgrade pip setuptools wheel || goto :error
  "%GBI_PY%" -m pip install --prefer-binary -r "%~dp0requirements.txt" || goto :error
)

set "PYTHONPATH=%~dp0;%PYTHONPATH%"
"%GBI_PY%" -m grav_bridge_i.web --open-browser
exit /b 0

:error
echo.
echo GRAV-BRIDGE-I could not start. Review the message above.
echo The environment location is:
echo   %GBI_ENV_ROOT%
pause
exit /b 1
