@echo off
title TG Matrix - OCR Captcha Plugin Installer

echo ============================================
echo   TG Matrix OCR Captcha Plugin Installer
echo ============================================
echo.
echo This script installs the OCR plugin next to
echo the client for image captcha recognition.
echo The client itself will NOT be modified.
echo.
echo Install path: %~dp0plugins\ocr
echo Estimated size: ~150MB (includes onnxruntime)
echo.

REM -- Check Python ----------------------------
python --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Python not found. Please install Python 3.8+
    echo.
    echo Download: https://www.python.org/downloads/
    echo Make sure to check "Add Python to PATH"
    echo.
    pause
    exit /b 1
)

for /f "tokens=2 delims= " %%v in ('python --version 2^>^&1') do set PYVER=%%v
echo [OK] Python %PYVER% detected
echo.

REM -- Set target directory ---------------------
set "PLUGIN_DIR=%~dp0plugins\ocr"

if exist "%PLUGIN_DIR%\ddddocr" (
    echo [INFO] OCR plugin already installed. Reinstall?
    set /p REINSTALL="Enter Y to reinstall, any other key to skip: "
    if /i not "%REINSTALL%"=="Y" (
        echo Skipped.
        pause
        exit /b 0
    )
    echo Cleaning old version...
    rmdir /s /q "%PLUGIN_DIR%" >nul 2>&1
)

REM -- Install ddddocr --------------------------
echo.
echo Installing ddddocr to %PLUGIN_DIR% ...
echo (First install downloads ~100MB, please wait)
echo.

pip install --target="%PLUGIN_DIR%" "ddddocr>=1.4.0" --no-warn-script-location -q

if %errorlevel% neq 0 (
    echo.
    echo [WARN] Default mirror failed, trying China mirror...
    pip install --target="%PLUGIN_DIR%" "ddddocr>=1.4.0" --no-warn-script-location -q -i https://pypi.tuna.tsinghua.edu.cn/simple

    if %errorlevel% neq 0 (
        echo.
        echo [ERROR] Install failed. Please run manually:
        echo   pip install --target="%PLUGIN_DIR%" ddddocr
        echo.
        pause
        exit /b 1
    )
)

REM -- Verify install ----------------------------
echo.
echo Verifying installation...
python -c "import sys; sys.path.insert(0, r'%PLUGIN_DIR%'); import ddddocr; print('ddddocr', ddddocr.__version__)" 2>nul

if %errorlevel% neq 0 (
    echo [WARN] Verification failed, but files are installed. Restart client to test.
) else (
    echo.
    echo ============================================
    echo   [SUCCESS] OCR plugin installed!
    echo ============================================
    echo.
    echo Restart TG Matrix client to enable image
    echo captcha recognition. No extra config needed.
    echo.
    echo To uninstall, just delete this folder:
    echo   %PLUGIN_DIR%
)

echo.
pause
