@echo off
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
chcp 65001 >nul
title Soar CSI SAP2000 V27 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:\Soar\SAP2000_MCP_V1.1.1\
    echo ============================================================
    endlocal
    pause
    popd
    exit /b 1
)
endlocal

echo.
echo ============================================================
echo   Soar CSI SAP2000 V27 MCP — V2 Installer
echo ============================================================
echo.

echo [1/3] 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/3] 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-SAP2-XXXX-XXXX-XXXX): "
> "%HERE%license.txt" echo !LICENSE!

:have_license

echo [3/3] 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.
echo   Next steps:
echo   1. Start CSI SAP2000 V27
echo   2. Open any .sdb model (or new empty model)
echo   3. Restart Cowork / Claude Desktop to see the MCP
echo   4. Try: "show model summary" or "list all frame sections"
echo.
popd
pause
endlocal
exit /b 0

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