@echo off
title XpenseAIQ
cd /d "%~dp0"
set PORT=3001

cls
echo.
echo   ========================================
echo        XpenseAIQ -- Starting Up...
echo   ========================================
echo.

:: Check if Node.js is installed
where node >nul 2>nul
if %errorlevel% neq 0 (
  echo   [ERROR] Node.js is not installed!
  echo.
  echo   Please install Node.js 18+ from:
  echo   https://nodejs.org
  echo.
  echo   After installing, double-click this file again.
  echo.
  start https://nodejs.org
  pause
  exit /b
)

for /f "tokens=1 delims=." %%a in ('node -v') do set NODE_VER=%%a
set NODE_VER=%NODE_VER:v=%
echo   [OK] Node.js detected

:: Install dependencies if needed
if not exist node_modules (
  echo   [INFO] Installing dependencies (first time only)...
  echo.
  npm install --production
  echo.
  if %errorlevel% neq 0 (
    echo   [ERROR] Failed to install dependencies.
    echo   Try running 'npm install' manually in this folder.
    pause
    exit /b
  )
  echo   [OK] Dependencies installed!
)

:: Check if already running
for /f "tokens=*" %%a in ('type .xpenseaiq.pid 2^>nul') do (
  tasklist /fi "PID eq %%a" 2>nul | find "node" >nul
  if not errorlevel 1 (
    echo   [OK] XpenseAIQ is already running!
    echo   Opening browser...
    start http://localhost:%PORT%
    echo.
    echo   To stop: double-click "Stop XpenseAIQ.bat"
    timeout /t 4 >nul
    exit /b
  )
)

echo.
echo   Starting XpenseAIQ in background...
echo.

:: Start server in background
start /b "" node server\index.mjs > .xpenseaiq.log 2>&1
for /f "tokens=2" %%a in ('tasklist /fi "imagename eq node.exe" /fo list ^| find "PID"') do (
  echo %%a> .xpenseaiq.pid
)

:: Wait for server
echo   Waiting for server to start...
timeout /t 3 /nobreak >nul

echo   [OK] XpenseAIQ is running in the background!
echo.
echo   Opening browser...
start http://localhost:%PORT%
echo.
echo   ========================================
echo    Server runs in background -- you can
echo    close this window safely.
echo.
echo    To stop: double-click
echo    "Stop XpenseAIQ.bat"
echo   ========================================
echo.
timeout /t 5 >nul
