@echo off
REM ── LOGGING INIT ──────────────────────────────────────────
if "%~1"=="--internal-logged" (
    shift
    goto :real_start
)
if not exist "%USERPROFILE%\.liangzimixin\logs" mkdir "%USERPROFILE%\.liangzimixin\logs" 2>nul
powershell -NoProfile -Command "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $OutputEncoding = [System.Text.Encoding]::UTF8; $log=\"$env:USERPROFILE\.liangzimixin\logs\deploy_test_beta_$(Get-Date -f 'yyyyMMdd_HHmmss').log\"; Write-Host \"[INFO] Deployment log will be saved to $log\"; & '%~f0' --internal-logged %* 2>&1 | Tee-Object -FilePath $log"
exit /b %errorlevel%
REM ──────────────────────────────────────────────────────────

:real_start
setlocal enabledelayedexpansion
chcp 65001 >nul 2>&1

REM ============================================================
REM  liangzimixin install script (Windows) - TEST ENVIRONMENT BETA
REM  Usage:
REM    liangzimixin_install_test_beta.bat <appId> <appSecret> [quantumAccount] [encryptionMode]
REM    liangzimixin_install_test_beta.bat --app-id <appId> --app-secret <appSecret> [--quantum-account <quantumAccount>] [--encryption-mode <mode>]
REM ============================================================

set "SCRIPT_VERSION=0.3.104-beta.3"
set "NPM_PACKAGE=liangzimixin"

set "SKIP_SELF_UPDATE=1"
set "APP_ID="
set "APP_SECRET="
set "QUANTUM_ACCOUNT="
set "ENCRYPTION_MODE="
set "QUANTUM_DISABLED=0"

REM -- Parse arguments -------------------------------------------------
:parse_args
if "%~1"=="" goto :parse_done
set "ARG=%~1"

if /i "%ARG%"=="--skip-self-update" (
    set "SKIP_SELF_UPDATE=1"
    shift
    goto :parse_args
)

if /i "%ARG%"=="--self-update" (
    set "SKIP_SELF_UPDATE=0"
    shift
    goto :parse_args
)

if /i "%ARG%"=="--beta" (
    shift
    goto :parse_args
)

if /i "%ARG%"=="--app-id" (
    if "%~2"=="" (
        echo [ERROR] --app-id requires a value
        exit /b 1
    )
    set "APP_ID=%~2"
    shift
    shift
    goto :parse_args
)

if /i "%ARG:~0,9%"=="--app-id=" (
    set "APP_ID=%ARG:~9%"
    shift
    goto :parse_args
)

if /i "%ARG%"=="--app-secret" (
    if "%~2"=="" (
        echo [ERROR] --app-secret requires a value
        exit /b 1
    )
    set "APP_SECRET=%~2"
    shift
    shift
    goto :parse_args
)

if /i "%ARG:~0,13%"=="--app-secret=" (
    set "APP_SECRET=%ARG:~13%"
    shift
    goto :parse_args
)

if /i "%ARG%"=="--quantum-account" (
    if "%~2"=="" (
        echo [ERROR] --quantum-account requires a value
        exit /b 1
    )
    set "QUANTUM_ACCOUNT=%~2"
    shift
    shift
    goto :parse_args
)

if /i "%ARG:~0,18%"=="--quantum-account=" (
    set "QUANTUM_ACCOUNT=%ARG:~18%"
    shift
    goto :parse_args
)

if /i "%ARG%"=="--encryption-mode" (
    if "%~2"=="" (
        echo [ERROR] --encryption-mode requires a value
        exit /b 1
    )
    set "ENCRYPTION_MODE=%~2"
    shift
    shift
    goto :parse_args
)

if /i "%ARG:~0,18%"=="--encryption-mode=" (
    set "ENCRYPTION_MODE=%ARG:~18%"
    shift
    goto :parse_args
)

if /i "%ARG%"=="--device-name" (
    if "%~2"=="" (
        echo [ERROR] --device-name requires a value
        exit /b 1
    )
    set "ENCRYPTION_MODE=%~2"
    shift
    shift
    goto :parse_args
)

if /i "%ARG:~0,14%"=="--device-name=" (
    set "ENCRYPTION_MODE=%ARG:~14%"
    shift
    goto :parse_args
)

if "%ARG%"=="--" (
    shift
    goto :parse_positionals
)

if "%ARG:~0,2%"=="--" (
    echo [ERROR] Unknown option: %ARG%
    exit /b 1
)

call :assign_positional "%~1"
if errorlevel 1 exit /b 1
shift
goto :parse_args

:parse_positionals
if "%~1"=="" goto :parse_done
call :assign_positional "%~1"
if errorlevel 1 exit /b 1
shift
goto :parse_positionals

:parse_done
if defined ENCRYPTION_MODE call :validate_encryption_mode "%ENCRYPTION_MODE%"
if errorlevel 1 exit /b 1
if /i "%ENCRYPTION_MODE%"=="not_enabled" (
    echo [WARN] encryptionMode=not_enabled detected, quantum encryption will be disabled
    set "QUANTUM_ACCOUNT="
    set "ENCRYPTION_MODE=quantum_and_plain"
    set "QUANTUM_DISABLED=1"
)
if not defined ENCRYPTION_MODE set "ENCRYPTION_MODE=quantum_and_plain"

set "TAG=beta"
set "REMOTE_SCRIPT_URL=https://unpkg.com/%NPM_PACKAGE%@beta/scripts/liangzimixin_install_test_beta.bat"

if "%APP_ID%"=="" goto :usage
if "%APP_SECRET%"=="" goto :usage
goto :main

:usage
echo.
echo liangzimixin install script v%SCRIPT_VERSION%
echo.
echo Usage:
echo   %~nx0 ^<appId^> ^<appSecret^> [quantumAccount] [encryptionMode]
echo   %~nx0 --app-id ^<appId^> --app-secret ^<appSecret^> [--quantum-account ^<quantumAccount^>] [--encryption-mode ^<mode^>]
echo   %~nx0 ... --self-update
echo.
echo   WARNING: This is the TEST ENVIRONMENT BETA script ^(env=test, tag=beta^)
echo.
echo Arguments:
echo   appId            App ID ^(required^)
echo   appSecret        App Secret ^(required^)
echo   quantumAccount   Quantum Account ID ^(optional^)
echo   encryptionMode   Encryption mode ^(optional: quantum_only / quantum_and_plain / not_enabled^)
echo.
echo Options:
echo   --app-id ^<appId^>                 App ID
echo   --app-secret ^<appSecret^>         App Secret
echo   --quantum-account ^<id^>           Quantum Account ID
echo   --encryption-mode ^<mode^>         Encryption mode
echo   --device-name ^<mode^>             Alias of --encryption-mode
echo   --skip-self-update  Skip script self-update check ^(default^)
echo   --self-update       Enable script self-update check
echo.
echo Notes:
echo   Named options support both --key value and --key=value formats
echo   --beta is accepted for compatibility, but this script always installs beta
echo.
exit /b 1

REM ============================================================
:main
echo.
echo =======================================================
echo   liangzimixin deploy ^(TEST ENV + BETA^)  v%SCRIPT_VERSION%
echo =======================================================
echo.

REM ============================================================
REM  Step 0: Script self-update check
REM ============================================================
if "%SKIP_SELF_UPDATE%"=="1" (
    echo [INFO] Skip self-update by default ^(use --self-update to enable^)
    goto :step1
)

echo [INFO] Step 0/4 - Checking for script updates...

set "REMOTE_VERSION="
REM Fetch latest version from npm registry (use PowerShell for JSON parsing)
for /f "usebackq delims=" %%a in (`powershell -NoProfile -Command "try { (Invoke-RestMethod -Uri 'https://registry.npmjs.org/%NPM_PACKAGE%/beta' -TimeoutSec 10).version } catch { }" 2^>nul`) do (
    set "REMOTE_VERSION=%%a"
)

if not defined REMOTE_VERSION (
    echo [WARN] Cannot check remote version, continuing with current version
    goto :step1
)

REM Semver comparison: prevent prerelease from rolling back to older latest
for /f "delims=- tokens=1" %%a in ("!REMOTE_VERSION!") do set "CLEAN_REMOTE=%%a"
for /f "delims=- tokens=1" %%a in ("!SCRIPT_VERSION!") do set "CLEAN_LOCAL=%%a"

for /f "tokens=1,2,3 delims=." %%a in ("!CLEAN_REMOTE!") do (
    set "R1=%%a" & set "R2=%%b" & set "R3=%%c"
)
for /f "tokens=1,2,3 delims=." %%a in ("!CLEAN_LOCAL!") do (
    set "L1=%%a" & set "L2=%%b" & set "L3=%%c"
)

set "SHOULD_UPDATE=0"
if !R1! GTR !L1! set "SHOULD_UPDATE=1"
if !R1! EQU !L1! (
    if !R2! GTR !L2! set "SHOULD_UPDATE=1"
    if !R2! EQU !L2! (
        if !R3! GTR !L3! set "SHOULD_UPDATE=1"
    )
)

if "%REMOTE_VERSION%"=="%SCRIPT_VERSION%" (
    echo [OK] Script is up to date ^(v%SCRIPT_VERSION%^)
    goto :step1
)

if "!SHOULD_UPDATE!"=="0" (
    echo [OK] Current script ^(v%SCRIPT_VERSION%^) is newer or equal to remote ^(v%REMOTE_VERSION%^)
    goto :step1
)

echo [INFO] New version found: %SCRIPT_VERSION% -^> %REMOTE_VERSION%, updating...
set "TEMP_SCRIPT=%TEMP%\liangzimixin_install_test_beta_new.bat"
curl -fsSL --connect-timeout 10 --max-time 30 "!REMOTE_SCRIPT_URL!" -o "%TEMP_SCRIPT%" 2>nul
if %errorlevel%==0 (
    echo [OK] Script updated to v%REMOTE_VERSION%
    if defined QUANTUM_ACCOUNT (
        if defined ENCRYPTION_MODE (
            call "%TEMP_SCRIPT%" --skip-self-update --app-id "%APP_ID%" --app-secret "%APP_SECRET%" --quantum-account "%QUANTUM_ACCOUNT%" --encryption-mode "%ENCRYPTION_MODE%"
        ) else (
            call "%TEMP_SCRIPT%" --skip-self-update --app-id "%APP_ID%" --app-secret "%APP_SECRET%" --quantum-account "%QUANTUM_ACCOUNT%"
        )
    ) else (
        if defined ENCRYPTION_MODE (
            call "%TEMP_SCRIPT%" --skip-self-update --app-id "%APP_ID%" --app-secret "%APP_SECRET%" --encryption-mode "%ENCRYPTION_MODE%"
        ) else (
            call "%TEMP_SCRIPT%" --skip-self-update --app-id "%APP_ID%" --app-secret "%APP_SECRET%"
        )
    )
    exit /b %errorlevel%
) else (
    echo [WARN] Script download failed, continuing with current version
    del /q "%TEMP_SCRIPT%" 2>nul
)

echo.

REM ============================================================
REM  Step 1: Install/update plugin
REM ============================================================
:step1
echo [INFO] Step 1/4 - Install/update liangzimixin plugin ^(beta^)...

REM Set npm registry to mirror to prevent timeouts
call npm config set registry https://registry.npmmirror.com 2>nul

call openclaw plugins list 2>nul | findstr /i "liangzimixin" >nul
if %errorlevel%==0 (
    echo [INFO] Plugin installed, switching/updating to beta...
    call openclaw plugins install liangzimixin@beta 2>&1
) else (
    echo [INFO] Plugin not installed, installing beta...
    call openclaw plugins install liangzimixin@beta 2>&1
)

REM Verify plugin is actually installed (don't rely on exit code, as
REM "already at latest" may return non-zero)
call openclaw plugins list 2>nul | findstr /i "liangzimixin" >nul
if %errorlevel% neq 0 (
    echo [ERROR] Plugin install/update failed, check network or permissions
    exit /b 1
)

echo [OK] Plugin ready ^(beta^)
echo.

REM ============================================================
REM  Step 2: Write configuration
REM ============================================================
echo [INFO] Step 2/4 - Writing configuration...

call openclaw channels add --channel liangzimixin --token "%APP_ID%" --password "%APP_SECRET%" 2>&1

if %errorlevel% neq 0 (
    echo [ERROR] Configuration write failed, check parameters
    exit /b 1
)

call openclaw config set channels.liangzimixin.enabled true 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Channel enable configuration write failed
    exit /b 1
)

call openclaw config set channels.liangzimixin.defaultAccount "default" 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Default account configuration write failed
    exit /b 1
)

call openclaw config set channels.liangzimixin.accounts.default.appId "%APP_ID%" 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] App ID configuration write failed
    exit /b 1
)

call openclaw config set channels.liangzimixin.accounts.default.appSecret "%APP_SECRET%" 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] App secret configuration write failed
    exit /b 1
)

if "%QUANTUM_DISABLED%"=="1" (
    call openclaw config set channels.liangzimixin.accounts.default.quantumAccount "" 2>&1
    if %errorlevel% neq 0 (
        echo [ERROR] Quantum account configuration cleanup failed
        exit /b 1
    )
) else if defined QUANTUM_ACCOUNT (
    call openclaw config set channels.liangzimixin.accounts.default.quantumAccount "%QUANTUM_ACCOUNT%" 2>&1
    if %errorlevel% neq 0 (
        echo [ERROR] Quantum account configuration write failed
        exit /b 1
    )
)

if defined ENCRYPTION_MODE (
    call openclaw config set channels.liangzimixin.accounts.default.encryptionMode "%ENCRYPTION_MODE%" 2>&1
    if %errorlevel% neq 0 (
        echo [ERROR] Encryption mode configuration write failed
        exit /b 1
    )
)

set "SUCCESS_FIELDS=appId / appSecret"
if "%QUANTUM_DISABLED%"=="1" (
    set "SUCCESS_FIELDS=!SUCCESS_FIELDS! / quantum disabled"
) else (
    if defined QUANTUM_ACCOUNT set "SUCCESS_FIELDS=!SUCCESS_FIELDS! / quantumAccount"
    if defined ENCRYPTION_MODE set "SUCCESS_FIELDS=!SUCCESS_FIELDS! / encryptionMode=!ENCRYPTION_MODE!"
)
echo [OK] Configuration saved (!SUCCESS_FIELDS!)

REM Set test environment
echo [INFO] Setting test environment ^(env=test^)...
call openclaw config set channels.liangzimixin.accounts.default.env "test" 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Test environment configuration failed
    exit /b 1
)
echo [OK] Test environment configured
echo.

REM ============================================================
REM  Step 3: Restart gateway
REM ============================================================
echo [INFO] Step 3/4 - Restarting OpenClaw gateway...

call openclaw gateway restart 2>&1

if %errorlevel% neq 0 (
    echo [WARN] Gateway restart command returned an error or timed out
) else (
    echo [OK] Gateway restart command sent
)
echo.

REM ============================================================
REM  Step 4 commented out
REM ============================================================
REM echo [INFO] Step 4/4 - Health check...
REM ...

echo [WARN] Step 4 skipped ^(health check^)
echo   Manual check:   openclaw status
echo.
echo [SUCCESS] Deploy script finished

endlocal
exit /b 0

:assign_positional
if not defined APP_ID (
    set "APP_ID=%~1"
    exit /b 0
)
if not defined APP_SECRET (
    set "APP_SECRET=%~1"
    exit /b 0
)
if not defined QUANTUM_ACCOUNT (
    set "QUANTUM_ACCOUNT=%~1"
    exit /b 0
)
if not defined ENCRYPTION_MODE (
    set "ENCRYPTION_MODE=%~1"
    exit /b 0
)
echo [ERROR] Unexpected extra positional argument: %~1
exit /b 1

:validate_encryption_mode
if /i "%~1"=="quantum_only" exit /b 0
if /i "%~1"=="quantum_and_plain" exit /b 0
if /i "%~1"=="not_enabled" exit /b 0
echo [ERROR] encryptionMode must be quantum_only, quantum_and_plain, or not_enabled
exit /b 1
