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

set "BUNDLED_NODE=%USERPROFILE%\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin"
set "BUNDLED_PNPM=%USERPROFILE%\.cache\codex-runtimes\codex-primary-runtime\dependencies\bin\fallback\pnpm.cmd"

if exist "%BUNDLED_PNPM%" goto bundled_check
where npm.cmd >nul 2>nul
if errorlevel 1 goto missing

if not exist "node_modules" goto npm_install
node -e "import('vite')" >nul 2>nul
if errorlevel 1 goto npm_repair
goto npm_run

:npm_repair
echo Existing dependencies are damaged. Reinstalling...
rmdir /s /q "%CD%\node_modules"

:npm_install
call npm.cmd install
if errorlevel 1 goto install_failed

:npm_run
call npm.cmd run dev -- --host 0.0.0.0 --port 4173
exit /b %errorlevel%

:bundled_check
set "PATH=%BUNDLED_NODE%;%PATH%"
if not exist "node_modules" goto bundled_install
"%BUNDLED_NODE%\node.exe" -e "import('vite')" >nul 2>nul
if errorlevel 1 goto bundled_repair
goto bundled_run

:bundled_repair
echo Existing dependencies are damaged. Reinstalling...
rmdir /s /q "%CD%\node_modules"

:bundled_install
call "%BUNDLED_PNPM%" install --frozen-lockfile
if errorlevel 1 goto install_failed

:bundled_run
call "%BUNDLED_PNPM%" dev --host 0.0.0.0 --port 4173
exit /b %errorlevel%

:install_failed
echo.
echo Dependency installation failed. Check the network, then run this launcher again.
pause
exit /b 1

:missing
echo No local web runtime was found.
echo Install Node.js or reopen this project in Codex, then retry.
pause
exit /b 1
