@echo off
:: 1. 强制切换到当前脚本所在的盘符 and 目录
cd /d "%~dp0"
SET "ROOT_DIR=%~dp0"

:: 2. 设置唯一的窗口标题并获取当前窗口的唯一 PID
SET "WTitle=MTIM_SERVICE_MANAGER_%RANDOM%"
title %WTitle%

for /f "tokens=2 delims=," %%A in ('tasklist /v /fo csv ^| findstr /i "%WTitle%"') do (
    set "MY_PID=%%~A"
)

:: 3. 注入全局局部环境变量
SET "PATH=%ROOT_DIR%node;%PATH%"
SET "PM2_LOCAL=.\node\pm2.cmd"
SET "TARGET_URL=http://localhost:6101/admin/"
SET "PYTHONPATH=%ROOT_DIR%mtim-service-qt;%ROOT_DIR%py\Lib\site-packages"

echo ======================================================
echo  [SYS] Starting services...
echo ======================================================

:: 4. 深度清理历史残留（修正为真正的进程名 qtpy.exe，秒开不卡顿）
taskkill /f /im nginx.exe >nul 2>&1
taskkill /f /im qtpy.exe >nul 2>&1
cmd /c "%PM2_LOCAL%" kill >nul 2>&1

:: ========================================================================
:: 【clear...】
:: ========================================================================
set "vbsFile=%TEMP%\win7_pm2_monitor.vbs"
echo Set wshShell = CreateObject("WScript.Shell") > "%vbsFile%"
echo Do >> "%vbsFile%"
echo     WScript.Sleep 1000 >> "%vbsFile%"
echo     Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") >> "%vbsFile%"
echo     Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process Where ProcessId = " ^& %MY_PID%) >> "%vbsFile%"
echo     ' 一旦主 CMD 窗口被用户点击 "X" 关闭 >> "%vbsFile%"
echo     If colProcesses.Count = 0 Then >> "%vbsFile%"
echo         ' 【绝杀：全系统无差别轰炸 qtpy.exe】连续多轮强杀，确保彻底赶尽杀绝！ >> "%vbsFile%"
echo         wshShell.Run "wmic process where ""name='qtpy.exe'"" call terminate", 0, True >> "%vbsFile%"
echo         wshShell.Run "taskkill /f /im qtpy.exe", 0, True >> "%vbsFile%"
echo         wshShell.Run "wmic process where ""name='qtpy.exe'"" call terminate", 0, True >> "%vbsFile%"
echo         wshShell.Run "taskkill /f /im qtpy.exe", 0, True >> "%vbsFile%"
echo         ' 【定点路径清除当前目录下的 node 进程（不误杀其他 Node）】 >> "%vbsFile%"
echo         wshShell.Run "cmd /c """"%PM2_LOCAL%"" kill"", 0, True >> "%vbsFile%"
echo         wshShell.Run "wmic process where ""name='node.exe' and commandline like '%%" ^& Replace("%ROOT_DIR%", "\", "\\") ^& "%%'"" call terminate", 0, True >> "%vbsFile%"
echo         ' 【清除 Nginx 残留】 >> "%vbsFile%"
echo         wshShell.Run "taskkill /f /im nginx.exe", 0, True >> "%vbsFile%"
echo         Exit Do >> "%vbsFile%"
echo     End If >> "%vbsFile%"
echo Loop >> "%vbsFile%"

:: 关键：使用独立进程空间启动 VBS，主窗口关闭它也不会死
start "" wscript.exe "%vbsFile%"
:: ========================================================================

:: 5. 启动 Nginx 服务
echo [SYS] Launching Nginx...
cd /d "%ROOT_DIR%nginx"
start "" nginx.exe
cd /d "%ROOT_DIR%"

:: 6. 启动 PM2 服务（异步启动，防止死锁）
echo [PM2] Launching apps via ecosystem.config.js...
start /b "" cmd /c "%PM2_LOCAL% start ecosystem.config.js"

:: 7. 延迟 3 秒确保服务就绪，然后唤醒浏览器
echo [SYS] Launching admin browser...
timeout /t 3 /nobreak >nul
start %TARGET_URL%

echo.
echo ======================================================
echo  STATUS: RUNNING
echo  - Keep this window open.
echo  - Press ANY KEY in this window to close all services.
echo  - Or click 'X' directly to close all services.
echo ======================================================
echo.

pause

:: ======================================================
:: 8. 手动按任意键退出时的清理
:: ======================================================
:CLEANUP
echo [CLEANUP] Shutting down project services...
cmd /c "%PM2_LOCAL%" kill >nul 2>&1
wmic process where "name='node.exe' and commandline like '%%%ROOT_DIR%:\=\\%%%'" call terminate >nul 2>&1
taskkill /f /im nginx.exe >nul 2>&1
taskkill /f /im qtpy.exe >nul 2>&1
exit
