cd %~dp0
@echo off
setlocal enabledelayedexpansion

:: 1. Environment Setup
SET "ROOT_DIR=%~dp0"
SET "PATH=%ROOT_DIR%node;%PATH%"
SET PM2_LOCAL=.\node\node_modules\.bin\pm2.cmd
SET APP_LIST=nginx backend-service
SET TARGET_URL=http://localhost:6101/admin/
SET "PYTHONPATH=%ROOT_DIR%mtim-service-qt;%ROOT_DIR%py\Lib\site-packages"

:: Get the Process ID (PID) of THIS cmd window for monitoring
for /f "tokens=2 delims==" %%a in ('wmic process where "name='cmd.exe' and CommandLine like '%%%~nx0%%'" get ParentProcessId /value 2^>nul') do set "MYPID=%%a"
if "%MYPID%"=="" set "MYPID=%ERRORLEVEL%"

:: 2. Create the Monitoring script (VBS)
:: This script ensures cleanup happens even if the CMD window is closed via the "X" button.
echo WScript.Sleep 5000 > cleanup.vbs
echo Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") >> cleanup.vbs
echo Do >> cleanup.vbs
echo     Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process Where ProcessId = %MYPID%") >> cleanup.vbs
echo     If colProcesses.Count = 0 Then Exit Do >> cleanup.vbs
echo     WScript.Sleep 2000 >> cleanup.vbs
echo Loop >> cleanup.vbs
:: Cleanup logic: 'pm2 kill' stops only the Node processes tracked by this PM2 instance.
echo Set WshShell = CreateObject("WScript.Shell") >> cleanup.vbs
echo WshShell.Run "cmd /c ""%PM2_LOCAL%"" kill & taskkill /f /im nginx.exe /f & taskkill /f /im 1.exe /t", 0, True >> cleanup.vbs
echo Set fso = CreateObject("Scripting.FileSystemObject") >> cleanup.vbs
echo fso.DeleteFile WScript.ScriptFullName >> cleanup.vbs

:: Start the background monitor minimized
start /min wscript.exe cleanup.vbs

:: 3. Start Processes
for %%a in (%APP_LIST%) do (
    call "%PM2_LOCAL%" describe %%a >nul 2>&1
    if !errorlevel! EQU 0 (
        echo [PM2] %%a is already running. Restarting...
        call "%PM2_LOCAL%" restart %%a
    ) else (
        echo [PM2] %%a not found. Starting fresh...
        call "%PM2_LOCAL%" start ecosystem.config.js --only %%a
    )
)

:: 4. Final Verification and Launch
echo.
call "%PM2_LOCAL%" list
timeout /t 3 /nobreak >nul
start %TARGET_URL%

echo.
echo ======================================================
echo  STATUS: RUNNING (Window PID: %MYPID%)
echo  - Closing this window will STOP all related processes.
echo  - CLEANUP: Uses 'pm2 kill' to avoid killing other Node apps.
echo ======================================================
echo.

pause

:: 5. Manual Exit Cleanup
echo [CLEANUP] Shutting down project services...
:: 'pm2 kill' terminates the PM2 daemon and all its managed processes via specific PIDs
call "%PM2_LOCAL%" kill
taskkill /f /im nginx.exe /f >nul 2>&1
taskkill /f /im 1.exe /t >nul 2>&1
exit