@echo off
title Class Generator - Portable Edition
cd /d "%~dp0"

echo.
echo ========================================
echo   Class Generator - Portable Edition
echo ========================================
echo.

:: Check if portable Node.js exists
if not exist "nodejs-portable\node.exe" (
    echo [ERROR] Node.js portable not found!
    echo.
    echo Please follow the setup instructions in PORTABLE_SETUP.txt
    echo.
    pause
    exit /b 1
)

:: Add portable Node.js to PATH for this session only
set PATH=%~dp0nodejs-portable;%PATH%

:: Verify Node.js is working
echo [1/3] Checking Node.js...
"%~dp0nodejs-portable\node.exe" --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Node.js is not working properly
    pause
    exit /b 1
)
echo       Node.js OK!

:: Check if node_modules exists
echo [2/3] Checking dependencies...
if not exist "node_modules" (
    echo       Installing dependencies...
    "%~dp0nodejs-portable\node.exe" "%~dp0nodejs-portable\node_modules\npm\bin\npm-cli.js" install
) else (
    echo       Dependencies OK!
)

:: Kill any existing servers on port 8080
echo [3/4] Cleaning up old servers...
taskkill /f /im node.exe >nul 2>&1
timeout /t 1 /nobreak >nul

:: Start the server in background
echo [4/4] Starting server...
echo.
echo ========================================
echo   Server starting on http://localhost:8080
echo   Opening browser automatically...
echo   Press Ctrl+C to stop
echo ========================================
echo.

:: Start server in background
start /b "" "%~dp0nodejs-portable\node.exe" server.js

:: Wait for server to start
timeout /t 2 /nobreak >nul

:: Open Firefox (REQUIRED - Edge/Chrome don't work in target environment)
echo Opening Firefox...

:: Try common Firefox locations
if exist "C:\Program Files\Mozilla Firefox\firefox.exe" (
    start "" "C:\Program Files\Mozilla Firefox\firefox.exe" http://localhost:8080
) else if exist "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" (
    start "" "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" http://localhost:8080
) else (
    :: Try via PATH
    start firefox http://localhost:8080 >nul 2>&1
    if %errorlevel% neq 0 (
        echo.
        echo [WARNING] Firefox not found!
        echo Please open Firefox manually: http://localhost:8080
        echo NOTE: Edge and Chrome will NOT work
        echo.
    )
)

echo.
echo Browser opened! Server is running in background.
echo Press any key to STOP the server and close...
pause >nul

:: Stop the server
echo.
echo Stopping server...
taskkill /f /im node.exe >nul 2>&1

:: If we get here, the server stopped
echo.
echo Server stopped
pause
