@echo off
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
chcp 65001 >nul
title Soar PowerPoint MCP — Installer (V2)

set "HERE=%~dp0"
set "EXE=%HERE%launcher.dist\launcher.exe"
pushd "%HERE%"

setlocal DISABLEDELAYEDEXPANSION
echo "%HERE%" | findstr /R "[()!^&]" >nul 2>&1
if not errorlevel 1 (
    echo.
    echo ============================================================
    echo   [X] ERROR: Install path contains special characters
    echo       such as parentheses, !, ^& or ^
    echo.
    echo   Current path: %HERE%
    echo.
    echo   Please move the folder to a simple path like:
    echo       D:\Claude\Soar_PPT_MCP_V1.1\
    echo ============================================================
    endlocal
    pause
    popd
    exit /b 1
)
endlocal

echo.
echo ============================================================
echo   Soar PowerPoint MCP — V2 Installer
echo ============================================================
echo.

echo [1/4] Checking launcher ...
if not exist "%EXE%" (
    echo   [X] launcher.dist\launcher.exe not found.
    echo       Please ensure the installation package is complete.
    goto :fail
)
echo   OK.

echo [2/4] License key
if exist "%HERE%license.txt" (
    for /f "usebackq delims=" %%L in ("%HERE%license.txt") do set "LICENSE=%%L"
    echo   Existing license.txt found: !LICENSE!
    set /p "CHANGE=  Change it? (y/N): "
    if /I "!CHANGE!"=="Y" goto :ask_license
    goto :have_license
)
:ask_license
set /p "LICENSE=  Paste license key (SOAR-XXXX-XXXX-XXXX-XXXX): "
> "%HERE%license.txt" echo !LICENSE!

:have_license

echo [3/4] Enabling "Trust access to VBA project object model" for run_vba ...
for %%V in (16.0 15.0 14.0) do (
    reg add "HKCU\Software\Microsoft\Office\%%V\PowerPoint\Security" /v AccessVBOM /t REG_DWORD /d 1 /f >nul 2>&1
)
echo   Done.

echo [4/4] Verifying license with Cloudflare ...
"%EXE%" --install-check
if errorlevel 1 (
    echo   [X] License invalid or server unreachable.
    goto :fail
)
echo   Modules loaded to RAM successfully.

echo Registering MCP with Claude Desktop / Cowork ...
"%EXE%" --register-mcp
if errorlevel 1 (
    echo   Warning: Auto-register failed. Configure manually using config\cowork_mcp.json.template
) else (
    echo   MCP registered successfully.
)

echo.
echo ============================================================
echo   Installation complete!
echo ============================================================
echo.
popd
pause
endlocal
exit /b 0

:fail
echo.
echo ============================================================
echo   [X] Installation FAILED. See errors above.
echo ============================================================
popd
pause
endlocal
exit /b 1
