@echo off
chcp 65001 >nul
setlocal EnableDelayedExpansion

rem Set basic variables
set "SCRIPT_DIR=%~dp0"
set "LOG_DIR=%SCRIPT_DIR%logs"
set "BACKEND_PID_FILE=%SCRIPT_DIR%backend.pid"

if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"
set "LOG_FILE=%LOG_DIR%\server_%date:~0,4%%date:~5,2%%date:~8,2%.log"

rem Clean up old processes and files
taskkill /F /IM python.exe /FI "WINDOWTITLE eq OpenWebUI*" >nul 2>&1
timeout /t 2 >nul

if exist "%BACKEND_PID_FILE%" del "%BACKEND_PID_FILE%"

goto :main

:write_log
echo [%date% %time%] %~1
echo [%date% %time%] %~1 >> "%LOG_FILE%"
exit /b

:start_backend
cd /d "%SCRIPT_DIR%backend"
call :write_log "Starting backend service..."
start "OpenWebUI Backend" /B cmd /c start_windows.bat
if errorlevel 1 (
    call :write_log "Failed to start backend"
    exit /b 1
)

timeout /t 5 >nul

for /f "tokens=2" %%a in ('wmic process where "commandline like '%%python%%' and name='python.exe'" get processid ^| findstr /r "[0-9]"') do (
    echo %%a > "%BACKEND_PID_FILE%"
    call :write_log "Backend started with PID: %%a"
    exit /b 0
)

call :write_log "Failed to get backend PID"
exit /b 1

:start
call :write_log "Starting backend service..."

call conda activate open-webui
if errorlevel 1 (
    call :write_log "Failed to activate conda environment"
    goto :cleanup
)

call :start_backend
if errorlevel 1 goto :cleanup

cd /d "%SCRIPT_DIR%"
call :write_log "Backend service started successfully"
exit /b 0

:cleanup
call :write_log "Start failed, cleaning up..."
call :stop
exit /b 1

:stop
call :write_log "Stopping services..."

if exist "%BACKEND_PID_FILE%" (
    for /f %%a in (%BACKEND_PID_FILE%) do (
        taskkill /F /T /PID %%a >nul 2>&1
        if not errorlevel 1 call :write_log "Stopped backend process (PID: %%a)"
    )
    del "%BACKEND_PID_FILE%"
)

for /f "tokens=2" %%a in ('wmic process where "commandline like '%%python%%' and name='python.exe'" get processid ^| findstr /r "[0-9]"') do (
    taskkill /F /T /PID %%a >nul 2>&1
    call :write_log "Stopped additional Python process (PID: %%a)"
)

call :write_log "All services stopped"
exit /b 0

:status
set "running=0"

if exist "%BACKEND_PID_FILE%" (
    for /f %%a in (%BACKEND_PID_FILE%) do (
        tasklist /FI "PID eq %%a" 2>nul | find "%%a" >nul
        if not errorlevel 1 (
            call :write_log "Backend is running (PID: %%a)"
            set /a running+=1
        )
    )
)

if %running% equ 1 (
    call :write_log "Backend service is running"
    exit /b 0
) else (
    call :write_log "Backend service is not running"
    exit /b 1
)

:main
if "%1"=="" (
    echo Usage: %~nx0 {start^|stop^|status}
    exit /b 1
)

if "%1"=="start" (
    call :stop
    timeout /t 2 >nul
    call :start
) else if "%1"=="stop" (
    call :stop
) else if "%1"=="status" (
    call :status
) else (
    echo Invalid command. Use: %~nx0 {start^|stop^|status}
    exit /b 1
)
exit /b %errorlevel%
