@echo off
echo ================================================
echo BigBrotherBot (B3) - Dependency Installation
echo ================================================
echo.
echo Installing required Python packages...
echo.

REM Locate Python executable (try `python` then `py`)
echo Checking for Python...
python --version >nul 2>&1
if errorlevel 1 (
    py --version >nul 2>&1
    if errorlevel 1 (
        echo ERROR: Python is not installed or not in PATH.
        echo Please install Python 3.8+ from https://www.python.org/downloads/ and ensure it's added to PATH.
        pause
        exit /b 1
    ) else (
        set "PYEXEC=py"
    )
) else (
    set "PYEXEC=python"
)

REM Ensure pip is available (prefer `python -m pip`)
echo Checking for pip (will try to install if missing)...
%PYEXEC% -m pip --version >nul 2>&1
if errorlevel 1 (
    echo pip not found. Attempting to install pip using ensurepip...
    %PYEXEC% -m ensurepip --upgrade >nul 2>&1
    %PYEXEC% -m pip install --upgrade pip setuptools wheel >nul 2>&1
    %PYEXEC% -m pip --version >nul 2>&1
    if errorlevel 1 (
        echo ensurepip did not provide pip or failed. Downloading get-pip.py...
        powershell -Command "Try { (New-Object Net.WebClient).DownloadFile('https://bootstrap.pypa.io/get-pip.py','%CD%\\get-pip.py') } Catch { exit 1 }"
        if errorlevel 1 (
            echo Failed to download get-pip.py. Please install pip manually.
            pause
            exit /b 1
        )
        %PYEXEC% "%CD%\\get-pip.py" >nul 2>&1
        del /q "%CD%\\get-pip.py" >nul 2>&1
        %PYEXEC% -m pip --version >nul 2>&1
        if errorlevel 1 (
            echo Failed to install pip automatically. Please install pip manually.
            pause
            exit /b 1
        )
    ) else (
        echo pip installed successfully via ensurepip.
    )
) else (
    echo pip is available.
)

REM Install core dependencies using the discovered Python executable
echo Installing core dependencies...
%PYEXEC% -m pip install pymysql>=1.0.2 python-dateutil>=2.8.0 feedparser>=6.0.0 requests>=2.25.0 packaging>=21.0

if errorlevel 1 (
    echo.
    echo Installation failed! Trying with --user flag...
    %PYEXEC% -m pip install --user pymysql>=1.0.2 python-dateutil>=2.8.0 feedparser>=6.0.0 requests>=2.25.0 packaging>=21.0
)

echo.
echo Installing optional dependencies...
%PYEXEC% -m pip install psycopg2-binary>=2.9.0 paramiko>=2.12.0 langdetect>=1.0.9
if errorlevel 1 (
    %PYEXEC% -m pip install --user psycopg2-binary>=2.9.0 paramiko>=2.12.0 langdetect>=1.0.9
)

echo.
echo ================================================
echo Installation completed!
echo.
echo You can now run B3 with:
echo python b3_run.py
echo ================================================
pause
