@echo off
setlocal EnableExtensions

set "SCRIPT_DIR=%~dp0"
pushd "%SCRIPT_DIR%" >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Failed to switch to project directory:
    echo %SCRIPT_DIR%
    pause
    exit /b 1
)

if not exist ".env" (
    echo [ERROR] .env file was not found.
    echo Copy .env.example to .env and fill in BOT_TOKEN, REMNAWAVE_* and DB_* values.
    popd
    pause
    exit /b 1
)

call :find_python
if errorlevel 1 (
    echo [ERROR] Python was not found in PATH.
    echo Install Python 3.12+ and make sure ^`py^` or ^`python^` is available.
    popd
    pause
    exit /b 1
)

call :ensure_venv
if errorlevel 1 (
    popd
    pause
    exit /b 1
)

echo [INFO] Installing dependencies...
".venv\Scripts\python.exe" -m pip install -e .
if errorlevel 1 (
    echo [ERROR] Failed to install dependencies
    popd
    pause
    exit /b 1
)

echo [INFO] Starting bot...
".venv\Scripts\python.exe" main.py
set "EXIT_CODE=%ERRORLEVEL%"

if not "%EXIT_CODE%"=="0" (
    echo [ERROR] Bot stopped with code %EXIT_CODE%
    popd
    pause
    exit /b %EXIT_CODE%
)

popd
exit /b 0

:find_python
set "BOOTSTRAP_PY="

py -3 --version >nul 2>&1
if not errorlevel 1 (
    set "BOOTSTRAP_PY=py -3"
    echo [INFO] Using bootstrap interpreter: %BOOTSTRAP_PY%
    exit /b 0
)

py --version >nul 2>&1
if not errorlevel 1 (
    set "BOOTSTRAP_PY=py"
    echo [INFO] Using bootstrap interpreter: %BOOTSTRAP_PY%
    exit /b 0
)

python --version >nul 2>&1
if not errorlevel 1 (
    set "BOOTSTRAP_PY=python"
    echo [INFO] Using bootstrap interpreter: %BOOTSTRAP_PY%
    exit /b 0
)

exit /b 1

:ensure_venv
set "RECREATE_VENV="

if not exist ".venv\Scripts\python.exe" (
    set "RECREATE_VENV=1"
)

if not defined RECREATE_VENV (
    ".venv\Scripts\python.exe" -c "import sys; print(sys.executable)" >nul 2>&1
    if errorlevel 1 (
        set "RECREATE_VENV=1"
    )
)

if defined RECREATE_VENV (
    if exist ".venv" (
        echo [WARN] Existing .venv is invalid or was created on another machine.
        echo [INFO] Recreating virtual environment...
        rmdir /s /q ".venv"
        if exist ".venv" (
            echo [ERROR] Failed to remove broken .venv
            exit /b 1
        )
    ) else (
        echo [INFO] Creating virtual environment...
    )

    %BOOTSTRAP_PY% -m venv .venv
    if errorlevel 1 (
        echo [ERROR] Failed to create .venv
        exit /b 1
    )
)

".venv\Scripts\python.exe" -m pip --version >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Virtual environment exists, but pip is unavailable.
    exit /b 1
)

exit /b 0
