@echo off
chcp 65001 >nul
title WorkBuddy Monitor
set "ROOT=%~dp0.."
cd /d "%ROOT%"

echo =============================================
echo   WorkBuddy Monitor - Token ÓÃÁ¿¼à¿ØÃæ°å
echo =============================================
echo.

:: Find Python
set PYTHON_CMD=
where python >nul 2>&1 && set PYTHON_CMD=python
if "%PYTHON_CMD%"=="" (
    if exist "C:\Python311\python.exe" set PYTHON_CMD=C:\Python311\python.exe
)
if "%PYTHON_CMD%"=="" (
    if exist "C:\Python312\python.exe" set PYTHON_CMD=C:\Python312\python.exe
)
if "%PYTHON_CMD%"=="" (
    if exist "C:\Python313\python.exe" set PYTHON_CMD=C:\Python313\python.exe
)
if "%PYTHON_CMD%"=="" (
    if exist "%LOCALAPPDATA%\Programs\Python\Python311\python.exe" set PYTHON_CMD=%LOCALAPPDATA%\Programs\Python\Python311\python.exe
)
if "%PYTHON_CMD%"=="" (
    echo [Error] Python not found! Please install Python 3.9+
    pause
    exit /b 1
)

echo Using: %PYTHON_CMD%
%PYTHON_CMD% --version

:: Check dependencies
echo.
echo [1/3] Checking dependencies...
%PYTHON_CMD% -c "import flask, cryptography" 2>nul
if %ERRORLEVEL% NEQ 0 (
    echo Installing dependencies...
    %PYTHON_CMD% -m pip install -r "%ROOT%\config\requirements.txt"
    if %ERRORLEVEL% NEQ 0 (
        echo [Error] pip install failed!
        pause
        exit /b 1
    )
    echo Dependencies installed
) else (
    echo Dependencies ready
)

:: Kill old process on port 5910
echo.
echo [2/3] Stopping old process...
for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":5910 " ^| findstr LISTENING') do (
    echo Found old PID: %%a, stopping...
    taskkill /f /pid %%a >nul 2>&1 && echo Old process stopped
)
timeout /t 1 /nobreak >nul

:: Start
echo.
echo [3/3] Starting monitor service...
start "WorkBuddy-Monitor" /MIN /B %PYTHON_CMD% "%ROOT%\run.py" --no-browser > "%ROOT%\artifacts\monitor.log" 2>&1

echo Done!
echo.
echo =============================================
echo   Dashboard: http://127.0.0.1:5910
echo   Log: %ROOT%\artifacts\monitor.log
echo   Press any key to stop the service
echo =============================================
echo.

:: Open browser
start http://127.0.0.1:5910

:: Wait for key press to stop
pause >nul
echo Stopping...
for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":5910 " ^| findstr LISTENING') do (
    taskkill /f /pid %%a >nul 2>&1
)
echo Service stopped.
timeout /t 2 /nobreak >nul
