@echo off
title Class Generator - Portable Edition (Safe Mode)
cd /d "%~dp0"
setlocal enabledelayedexpansion

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

:: ============================================
:: STEP 1: Check portable Node.js
:: ============================================
echo [1/7] Checking Node.js...
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.
    echo TROUBLESHOOTING:
    echo - Run DIAGNOSTIC.bat to check your system
    echo - Ensure nodejs-portable folder exists
    echo.
    goto :error_exit
)

:: Verify Node.js actually runs
"%~dp0nodejs-portable\node.exe" --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Node.js exists but won't run!
    echo.
    echo POSSIBLE CAUSES:
    echo - Antivirus blocking node.exe
    echo - Missing Visual C++ Redistributable
    echo - Download corrupted
    echo.
    echo SOLUTIONS:
    echo 1. Add exception in antivirus for this folder
    echo 2. Run DIAGNOSTIC.bat for detailed check
    echo 3. Re-download portable Node.js
    echo.
    goto :error_exit
)
echo       OK - Node.js working

:: ============================================
:: STEP 2: Check dependencies
:: ============================================
echo [2/7] Checking dependencies...
if not exist "node_modules" (
    echo       Installing dependencies (this may take a few minutes)...

    "%~dp0nodejs-portable\node.exe" "%~dp0nodejs-portable\node_modules\npm\bin\npm-cli.js" install

    if !errorlevel! neq 0 (
        echo [ERROR] Dependency installation failed!
        echo.
        echo POSSIBLE CAUSES:
        echo - No internet connection
        echo - Firewall blocking npm
        echo - Disk space full
        echo.
        echo SOLUTION: Check DIAGNOSTIC_REPORT.txt
        goto :error_exit
    )
    echo       Dependencies installed successfully
) else (
    echo       OK - Dependencies present
)

:: ============================================
:: STEP 3: Port cleanup (SMART)
:: ============================================
echo [3/7] Checking port 8080...

:: Check if port is in use
netstat -ano | findstr :8080 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo       WARNING: Port 8080 is in use

    :: Find the PID
    for /f "tokens=5" %%a in ('netstat -ano ^| findstr :8080 ^| findstr LISTENING') do (
        set PORT_PID=%%a

        :: Check if it's a node.exe process
        tasklist /fi "pid eq !PORT_PID!" | findstr node.exe >nul
        if !errorlevel! equ 0 (
            echo       Killing previous Node.js server (PID: !PORT_PID!)...
            taskkill /f /pid !PORT_PID! >nul 2>&1
            timeout /t 1 /nobreak >nul
        ) else (
            echo       ERROR: Port 8080 used by another program!
            echo.
            echo SOLUTION:
            echo - Close the other program
            echo - Or edit server.js to use a different port
            echo.
            goto :error_exit
        )
    )
) else (
    echo       OK - Port 8080 available
)

:: ============================================
:: STEP 4: Critical files check
:: ============================================
echo [4/7] Verifying project files...
set FILES_MISSING=0

if not exist "server.js" (
    echo       ERROR: server.js missing
    set /a FILES_MISSING+=1
)
if not exist "index.html" (
    echo       ERROR: index.html missing
    set /a FILES_MISSING+=1
)
if not exist "src\Application.js" (
    echo       ERROR: src\Application.js missing
    set /a FILES_MISSING+=1
)

if !FILES_MISSING! gtr 0 (
    echo.
    echo [ERROR] Critical files missing! Cannot start.
    echo.
    goto :error_exit
)
echo       OK - All files present

:: ============================================
:: STEP 5: Start server with logging
:: ============================================
echo [5/7] Starting server...

:: Create logs directory if needed
if not exist "logs" mkdir logs

:: Start server with log output
start /b "" "%~dp0nodejs-portable\node.exe" server.js > logs\server.log 2>&1

:: Save the start time for timeout
set START_TIME=%time%

:: ============================================
:: STEP 6: Wait for server (SMART WAIT)
:: ============================================
echo [6/7] Waiting for server to initialize...

:: Try for max 10 seconds
set /a TIMEOUT=10
set /a COUNTER=0

:wait_for_server
if !COUNTER! geq !TIMEOUT! (
    echo.
    echo [ERROR] Server did not start within !TIMEOUT! seconds
    echo.
    echo Check logs\server.log for error details
    echo.
    type logs\server.log
    echo.
    goto :cleanup_and_exit
)

:: Try to connect to the server (curl-less check)
powershell -Command "(New-Object Net.WebClient).DownloadString('http://localhost:8080')" >nul 2>&1
if %errorlevel% equ 0 (
    echo       OK - Server is responding!
    goto :server_ready
)

:: Wait 1 second and try again
timeout /t 1 /nobreak >nul
set /a COUNTER+=1
goto :wait_for_server

:server_ready

:: ============================================
:: STEP 7: Open browser
:: ============================================
echo [7/7] Opening Firefox...

:: FIREFOX ONLY - Edge and Chrome don't work in target environment
:: Try to find and launch Firefox
set FIREFOX_FOUND=0

:: Common Firefox locations - check in order
if exist "C:\Program Files\Mozilla Firefox\firefox.exe" (
    start "" "C:\Program Files\Mozilla Firefox\firefox.exe" http://localhost:8080
    set FIREFOX_FOUND=1
)

if !FIREFOX_FOUND! equ 0 (
    if exist "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" (
        start "" "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" http://localhost:8080
        set FIREFOX_FOUND=1
    )
)

if !FIREFOX_FOUND! equ 0 (
    where firefox >nul 2>&1
    if !errorlevel! equ 0 (
        start firefox http://localhost:8080
        set FIREFOX_FOUND=1
    )
)

if !FIREFOX_FOUND! equ 0 (
    echo.
    echo [WARNING] Firefox not found automatically
    echo.
    echo Please open Firefox manually and go to:
    echo   http://localhost:8080
    echo.
    echo NOTE: Edge and Chrome will NOT work in your environment
    echo       You MUST use Firefox
    echo.
)

echo.
echo ========================================
echo   SUCCESS! Server is running
echo ========================================
echo.
echo   URL: http://localhost:8080
echo   Logs: logs\server.log
echo.
echo   Press any key to STOP the server...
echo ========================================
echo.

pause >nul

:: ============================================
:: CLEANUP: Stop server
:: ============================================
:cleanup_and_exit
echo.
echo Stopping server...

:: Find and kill only our Node.js instance on port 8080
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :8080 ^| findstr LISTENING') do (
    tasklist /fi "pid eq %%a" | findstr node.exe >nul
    if !errorlevel! equ 0 (
        echo Killing Node.js process (PID: %%a)
        taskkill /f /pid %%a >nul 2>&1
    )
)

echo Server stopped
echo.
pause
exit /b 0

:: ============================================
:: ERROR EXIT
:: ============================================
:error_exit
echo.
echo ========================================
echo   STARTUP FAILED
echo ========================================
echo.
echo Run DIAGNOSTIC.bat for detailed analysis
echo Check logs\server.log if server started
echo.
pause
exit /b 1
