@echo off
setlocal EnableDelayedExpansion

REM ============================================================
REM 一键安装开发环境及四个 AI CLI 工具 (中国网络优化版)
REM - Windows Terminal
REM - Node.js (配置 npm 国内镜像)
REM - Claude Code / Codex CLI / Gemini CLI / Droid CLI / OpenClaw
REM ============================================================

REM --- 0. 检查管理员权限 ---
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo "请以管理员身份运行此脚本！（右键 > 以管理员身份运行）"
    timeout /t 5 >nul 2>&1
    goto :END
)

REM --- 0.1 检查 PowerShell 是否可用（用于部分操作） ---
where powershell >nul 2>&1
if %errorlevel% neq 0 (
    echo "未检测到 PowerShell，本脚本需要 PowerShell 支持。"
    echo "请在支持 PowerShell 的 Windows 10/11 环境下运行。"
    goto :END
)

REM --- 0.2 配置PowerShell执行策略 ---
echo 正在配置PowerShell执行策略...
powershell -NoProfile -Command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine -Force" >nul 2>&1
if %errorlevel% neq 0 (
    echo "PowerShell执行策略配置失败，可能会影响后续操作。"
) else (
    echo "PowerShell执行策略配置完成。"
)

set "SCRIPT_DIR=%~dp0"
set "DEFAULT_GIT_TUNA_INSTALLER_URL=https://mirror.tuna.tsinghua.edu.cn/github-release/git-for-windows/git/v2.52.0.windows.1/Git-2.52.0-64-bit.exe"
set "DEFAULT_GIT_SDU_INSTALLER_URL=https://mirrors.sdu.edu.cn/github-release/git-for-windows_git/v2.52.0.windows.1/Git-2.52.0-64-bit.exe"
set "DEFAULT_GIT_NJU_INSTALLER_URL=https://mirrors.nju.edu.cn/github-release/git-for-windows/git/LatestRelease/Git-2.52.0-64-bit.exe"
set "DEFAULT_GIT_USTC_INSTALLER_URL=https://mirrors.ustc.edu.cn/github-release/git-for-windows/git/LatestRelease/Git-2.52.0-64-bit.exe"
set "VC_REDIST_URL=https://aka.ms/vc14/vc_redist.x64.exe"
set "NODE_INSTALLER_URL=https://registry.npmmirror.com/-/binary/node/v24.13.1/node-v24.13.1-x64.msi"
set "GIT_NJU_LIST_URL=https://mirrors.nju.edu.cn/github-release/git-for-windows/git/LatestRelease/"
set "GIT_USTC_LIST_URL=https://mirrors.ustc.edu.cn/github-release/git-for-windows/git/LatestRelease/"
set "GIT_SDU_LIST_URL=https://mirrors.sdu.edu.cn/github-release/git-for-windows_git/"
set "GIT_TUNA_LIST_URL=https://mirror.tuna.tsinghua.edu.cn/github-release/git-for-windows/git/LatestRelease/"
echo ">>> 开始环境检查与安装..."

REM --- 1. 安装 Node.js 并确保 npm 可用 ---
call :EnsureNodeNpm
if not "%NODE_AVAILABLE%"=="1" (
    echo "Node.js 或 npm 无法正常使用，后续基于 npm 的 CLI 安装步骤将无法执行。"
    goto :END
)

REM --- 2. 配置 npm 国内镜像 ---
call :ConfigNpmMirror

REM --- 3. 安装/更新各 CLI 工具 ---
echo.
echo "[3/8] 安装 Claude Code (@anthropic-ai/claude-code)..."
where claude >nul 2>&1
if %errorlevel%==0 (
    echo "检测到 Claude Code 已安装。"
    choice /C YyNn /T 3 /D n /M "是否更新 Claude Code 到最新版本? (Y/N，默认 N，3 秒后自动选择默认值)："
    if errorlevel 3 (
        echo "已选择不更新 Claude Code，跳过此步骤。"
    ) else (
        echo "将更新 Claude Code 到最新版本..."
        cmd /c "npm install -g @anthropic-ai/claude-code@latest --registry=https://registry.npmmirror.com"
        if errorlevel 1 (
            echo "Claude Code 安装/更新失败，请检查网络。"
        ) else (
            echo "Claude Code 安装/更新完成。"
        )
    )
) else (
    echo "未检测到 Claude Code。"
    choice /C YyNn /T 5 /D y /M "是否安装 Claude Code? (Y/N，默认 Y，5 秒后自动选择默认值)："
    if errorlevel 3 (
        echo "已选择不安装 Claude Code，跳过此步骤。"
    ) else (
        echo "正在安装 Claude Code..."
        cmd /c "npm install -g @anthropic-ai/claude-code@latest --registry=https://registry.npmmirror.com"
        if errorlevel 1 (
            echo "Claude Code 安装失败，请检查网络。"
        ) else (
            echo "Claude Code 安装完成。"
        )
    )
)

echo.
echo "[4/8] 安装 Codex CLI (@openai/codex)..."
where codex >nul 2>&1
if %errorlevel%==0 (
    echo "检测到 Codex 已安装。"
    choice /C YyNn /T 3 /D n /M "是否更新 Codex CLI 到最新版本? (Y/N，默认 N，3 秒后自动选择默认值)："
    if errorlevel 3 (
        echo "已选择不更新 Codex CLI，跳过此步骤。"
    ) else (
        echo "将更新 Codex CLI 到最新版本..."
        call :InstallVcRuntimeForCodex
        cmd /c "npm install -g @openai/codex --registry=https://registry.npmmirror.com"
        if errorlevel 1 (
            echo "Codex CLI 安装/更新失败。"
        ) else (
            echo "Codex CLI 安装/更新完成。"
        )
    )
) else (
    echo "未检测到 Codex CLI。"
    choice /C YyNn /T 5 /D y /M "是否安装 Codex CLI? (Y/N，默认 Y，5 秒后自动选择默认值)："
    if errorlevel 3 (
        echo "已选择不安装 Codex CLI，跳过此步骤。"
    ) else (
        echo "正在安装 Codex CLI..."
        call :InstallVcRuntimeForCodex
        cmd /c "npm install -g @openai/codex --registry=https://registry.npmmirror.com"
        if errorlevel 1 (
            echo "Codex CLI 安装失败。"
        ) else (
            echo "Codex CLI 安装完成。"
        )
    )
)

echo.
echo "[5/8] 安装 Gemini CLI (@google/gemini-cli)..."
where gemini >nul 2>&1
if %errorlevel%==0 (
    echo "检测到 Gemini CLI 已安装。"
    choice /C YyNn /T 3 /D n /M "是否更新 Gemini CLI 到最新版本? (Y/N，默认 N，3 秒后自动选择默认值)："
    if errorlevel 3 (
        echo "已选择不更新 Gemini CLI，跳过此步骤。"
    ) else (
        echo "将更新 Gemini CLI 到最新版本..."
        cmd /c "npm install -g @google/gemini-cli@latest --registry=https://registry.npmmirror.com"
        if errorlevel 1 (
            echo "Gemini CLI 安装/更新失败。"
        ) else (
            echo "Gemini CLI 安装/更新完成。"
        )
    )
) else (
    echo "未检测到 Gemini CLI。"
    choice /C YyNn /T 5 /D y /M "是否安装 Gemini CLI? (Y/N，默认 Y，5 秒后自动选择默认值)："
    if errorlevel 3 (
        echo "已选择不安装 Gemini CLI，跳过此步骤。"
    ) else (
        echo "正在安装 Gemini CLI..."
        cmd /c "npm install -g @google/gemini-cli@latest --registry=https://registry.npmmirror.com"
        if errorlevel 1 (
            echo "Gemini CLI 安装失败。"
        ) else (
            echo "Gemini CLI 安装完成。"
        )
    )
)

echo.
echo "[6/8] 安装 Droid CLI (factory.ai)..."
where droid >nul 2>&1
if %errorlevel%==0 (
    echo "检测到 Droid 已安装。"
    choice /C YyNn /T 3 /D n /M "检测到 Droid 已安装，是否通过官方脚本重新安装/更新? (Y/N，默认 N，3 秒后自动选择默认值)："
    if errorlevel 3 (
        echo "已选择不重新安装/更新 Droid，跳过此步骤。"
    ) else (
        echo "通过官方脚本重新安装/更新 Droid CLI..."
        powershell -NoProfile -Command "$ProgressPreference='SilentlyContinue'; try { Invoke-Expression (Invoke-WebRequest -UseBasicParsing -Uri 'https://app.factory.ai/cli/windows').Content; exit 0 } catch { Write-Host '从 factory.ai 下载 Droid 官方安装脚本失败。' -ForegroundColor Yellow; if ($_.Exception) { Write-Host $_.Exception.Message -ForegroundColor Red; if ($_.Exception.Response -and $_.Exception.Response.StatusCode) { Write-Host ('HTTP 状态码: ' + [int]$_.Exception.Response.StatusCode) -ForegroundColor Red } } exit 1 }"
        if errorlevel 1 (
            echo "Droid CLI 安装失败，请检查网络或稍后重试。"
        ) else (
            echo "Droid CLI 安装完成。"
        )
    )
) else (
    echo "未检测到 Droid CLI。"
    choice /C YyNn /T 3 /D n /M "未检测到 Droid CLI，是否通过官方脚本安装? (Y/N，默认 N，3 秒后自动选择默认值)："
    if errorlevel 3 (
        echo "已选择不安装 Droid CLI，跳过此步骤。"
    ) else (
        echo "通过官方脚本安装 Droid CLI..."
        powershell -NoProfile -Command "$ProgressPreference='SilentlyContinue'; try { Invoke-Expression (Invoke-WebRequest -UseBasicParsing -Uri 'https://app.factory.ai/cli/windows').Content; exit 0 } catch { Write-Host '从 factory.ai 下载 Droid 官方安装脚本失败。' -ForegroundColor Yellow; if ($_.Exception) { Write-Host $_.Exception.Message -ForegroundColor Red; if ($_.Exception.Response -and $_.Exception.Response.StatusCode) { Write-Host ('HTTP 状态码: ' + [int]$_.Exception.Response.StatusCode) -ForegroundColor Red } } exit 1 }"
        if errorlevel 1 (
            echo "Droid CLI 安装失败，请检查网络或稍后重试。"
        ) else (
            echo "Droid CLI 安装完成。"
        )
    )
)

echo.
echo "安装 OpenClaw CLI (openclaw)..."
where openclaw >nul 2>&1
if %errorlevel%==0 (
    echo "检测到 OpenClaw 已安装。"
    choice /C YyNn /T 5 /D y /M "是否更新 OpenClaw 到最新版本? (Y/N，默认 Y，5 秒后自动选择默认值)："
    if errorlevel 3 (
        echo "已选择不更新 OpenClaw，跳过此步骤。"
    ) else (
        echo "将更新 OpenClaw 到最新版本..."
        cmd /c "npm install -g openclaw@latest --registry=https://registry.npmmirror.com"
        if errorlevel 1 (
            echo "OpenClaw 安装/更新失败。"
        ) else (
            echo "OpenClaw 安装/更新完成。"
        )
    )
) else (
    choice /C YyNn /T 5 /D y /M "是否安装 OpenClaw? (Y/N，默认 Y，5 秒后自动选择默认值)："
    if errorlevel 3 (
        echo "已选择不安装 OpenClaw，跳过此步骤。"
    ) else (
        echo "正在安装 OpenClaw..."
        cmd /c "npm install -g openclaw@latest --registry=https://registry.npmmirror.com"
        if errorlevel 1 (
            echo "OpenClaw 安装失败。"
        ) else (
            echo "OpenClaw 安装完成。"
        )
    )
)

REM --- 4. 安装 Git (推荐) ---
call :InstallGit

REM --- 5. 配置各 CLI 的 Token ---
call :ConfigTokens

REM --- 6. 推荐安装 Windows Terminal 以获得最佳命令行体验 ---
call :InstallWindowsTerminal

REM --- 结束 ---
:END
echo.
echo "=============================================="
echo "所有任务执行完毕（如上有錯误请先处理）。"
echo "1. 如命令 (claude-code / codex / gemini / droid / openclaw) 无法识别，请关闭当前窗口重新打开。"
echo "2. 使用 CLI 时如需代理，请自行配置系统代理或环境变量 (HTTP_PROXY / HTTPS_PROXY)。"
echo "3. 若要登录官方账号，请根据各 CLI 文档执行对应登录命令。"
echo "4. 为获得最佳命令行体验，强烈建议安装 Windows Terminal（本脚本已在最后尝试为你打开安装页面）。"
echo "=============================================="
echo.
echo "按任意键退出..."
pause >nul
endlocal
exit /b 0


REM ============================================================
REM 函数区
:InstallWindowsTerminal
echo.
echo "[8/8] 安装 Windows Terminal (推荐)..."
where wt.exe >nul 2>&1
if %errorlevel%==0 (
    echo "已检测到 Windows Terminal，跳过此步骤。"
    call :ConfigWindowsTerminalContextMenu
    goto :eof
)

echo "未检测到 Windows Terminal。"
echo "强烈建议安装 Windows Terminal，否则部分命令行工具可能出现编码、颜色或交互异常。"
echo "即将尝试打开 Microsoft Store 的 Windows Terminal 页面，请在商店中点击安装。"
start "" "ms-windows-store://pdp/?productid=9N0DX20HK701" >nul 2>&1
if %errorlevel% neq 0 (
    echo "无法自动打开 Microsoft Store，请在 Microsoft Store 中手动搜索并安装“Windows Terminal”。"
)
echo.
set "WT_INSTALL_DONE="
set /p WT_INSTALL_DONE=是否已在 Microsoft Store 中完成 Windows Terminal 安装? ^(Y/N, 默认 N^): 
if /I "%WT_INSTALL_DONE%"=="Y" (
    echo "将尝试使用 Windows Terminal 配置资源管理器右键菜单..."
    set "USE_POWERSHELL_MENU="
    where wt.exe >nul 2>&1
    if %errorlevel%==0 (
        call :ConfigWindowsTerminalContextMenu
    ) else (
        echo "仍未检测到 Windows Terminal，将回退为 PowerShell 菜单。"
        set "USE_POWERSHELL_MENU=1"
        call :ConfigWindowsTerminalContextMenu
    )
) else (
echo "将使用 PowerShell 配置资源管理器右键菜单（替代 Windows Terminal）。"
    set "USE_POWERSHELL_MENU=1"
    call :ConfigWindowsTerminalContextMenu
)
goto :eof


:InstallVcRuntimeForCodex
echo.
echo "正在准备安装 Codex CLI 所需的 Microsoft Visual C++ 运行库 (vc_redist.x64)..."
set "VC_DLL_MISSING=0"
if not exist "%SystemRoot%\System32\vcruntime140.dll" set "VC_DLL_MISSING=1"
if not exist "%SystemRoot%\System32\msvcp140.dll" set "VC_DLL_MISSING=1"
if "%VC_DLL_MISSING%"=="0" (
    echo "检测到 System32 目录中已存在 VC++ 140 运行库 DLL，跳过 vc_redist.x64 安装步骤。"
    goto :eof
)
set "VC_REDIST_EXE=%TEMP%\vc_redist.x64.exe"

if exist "%VC_REDIST_EXE%" (
    del /f /q "%VC_REDIST_EXE%" >nul 2>&1
)

powershell -NoProfile -Command "$ProgressPreference='SilentlyContinue'; try { Invoke-WebRequest -Uri '%VC_REDIST_URL%' -OutFile '%VC_REDIST_EXE%' -UseBasicParsing; exit 0 } catch { Write-Host '下载 VC++ 运行库安装包失败。' -ForegroundColor Yellow; if ($_.Exception) { Write-Host $_.Exception.Message -ForegroundColor Red; if ($_.Exception.Response -and $_.Exception.Response.StatusCode) { Write-Host ('HTTP 状态码: ' + [int]$_.Exception.Response.StatusCode) -ForegroundColor Red } } exit 1 }"
if errorlevel 1 (
    echo "VC++ 运行库下载失败，将继续 Codex CLI 安装（可能在编译/运行时失败）。"
    goto :eof
)

echo "正在静默安装 Microsoft Visual C++ 运行库 (vc_redist.x64)..."
start "" /wait "%VC_REDIST_EXE%" /install /quiet /norestart
if errorlevel 1 (
    echo "VC++ 运行库安装过程出现错误（可尝试手动运行安装包: %VC_REDIST_EXE%）。"
) else (
    echo "VC++ 运行库安装完成。"
)

del /f /q "%VC_REDIST_EXE%" >nul 2>&1
goto :eof


:InstallGit
echo.
echo "[7/8] 安装 Git (推荐)..."

where git >nul 2>&1
if %errorlevel%==0 (
    set "GIT_VER_STR="
    for /f "delims=" %%G in ('git --version 2^>nul') do set "GIT_VER_STR=%%G"
    if not "!GIT_VER_STR!"=="" (
        echo "检测到 Git 已安装: !GIT_VER_STR!"
    ) else (
        echo "检测到 Git 已安装。"
    )
    echo "如需重新安装或更新，请手动访问 Git 官网或镜像站。"
    goto :eof
)

set "GIT_INSTALLER_URL="
set "GIT_TUNA_FALLBACK_URL=%DEFAULT_GIT_TUNA_INSTALLER_URL%"
set "GIT_SDU_FALLBACK_URL=%DEFAULT_GIT_SDU_INSTALLER_URL%"
set "GIT_NJU_FALLBACK_URL=%DEFAULT_GIT_NJU_INSTALLER_URL%"
set "GIT_USTC_FALLBACK_URL=%DEFAULT_GIT_USTC_INSTALLER_URL%"
set "GIT_URL_FILE=%TEMP%\git-latest-url.txt"

echo "正在从 NJU 镜像检测最新 Git for Windows 64 位安装包版本..."
powershell -NoProfile -Command "$ProgressPreference='SilentlyContinue'; $base='%GIT_NJU_LIST_URL%'; $headers=@{ 'User-Agent'='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0'; 'Accept'='text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'; 'Accept-Language'='zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5'; 'Referer'=$base; 'Cache-Control'='no-cache'; 'Pragma'='no-cache' }; try { $response=Invoke-WebRequest -UseBasicParsing -Uri $base -Headers $headers; $content=$response.Content; $marker='href=' + [char]34 + 'Git-'; $hrefStart=$content.IndexOf($marker); if($hrefStart -lt 0){ Write-Host '未在 NJU LatestRelease 页面中找到 Git 64 位安装包链接。' -ForegroundColor Yellow; $debugFile=Join-Path $env:TEMP 'wq-nju-latestrelease.html'; $content | Set-Content -Path $debugFile -Encoding UTF8; Write-Host ('NJU LatestRelease 页面内容已保存到: ' + $debugFile) -ForegroundColor Yellow; exit 1 }; $hrefStart=$hrefStart + $marker.Length; $quote=[char]34; $hrefEnd=$content.IndexOf($quote,$hrefStart); if($hrefEnd -lt 0){ Write-Host '未在 NJU LatestRelease 页面中找到 Git 64 位安装包链接（未找到结束引号）。' -ForegroundColor Yellow; $debugFile=Join-Path $env:TEMP 'wq-nju-latestrelease.html'; $content | Set-Content -Path $debugFile -Encoding UTF8; Write-Host ('NJU LatestRelease 页面内容已保存到: ' + $debugFile) -ForegroundColor Yellow; exit 1 }; $file=$content.Substring($hrefStart,$hrefEnd-$hrefStart); $url=$base + $file; $url | Set-Content -Encoding ASCII '%GIT_URL_FILE%'; exit 0 } catch { Write-Host '获取 NJU Git LatestRelease 页面失败：' -ForegroundColor Yellow; if ($_.Exception) { Write-Host $_.Exception.Message -ForegroundColor Red; if ($_.Exception.Response -and $_.Exception.Response.StatusCode) { Write-Host ('HTTP 状态码: ' + [int]$_.Exception.Response.StatusCode) -ForegroundColor Red } } exit 1 }"
if errorlevel 1 (
    del /f /q "%GIT_URL_FILE%" >nul 2>&1
    echo "从 NJU 镜像解析最新版本失败，将尝试从 USTC 镜像解析..."
    powershell -NoProfile -Command "$ProgressPreference='SilentlyContinue'; $base='%GIT_USTC_LIST_URL%'; $headers=@{ 'User-Agent'='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0'; 'Accept'='text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'; 'Accept-Language'='zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5'; 'Referer'=$base; 'Cache-Control'='no-cache'; 'Pragma'='no-cache' }; try { $response=Invoke-WebRequest -UseBasicParsing -Uri $base -Headers $headers; $content=$response.Content; $marker='href=' + [char]34 + '/github-release/git-for-windows/git/LatestRelease/Git-'; $hrefStart=$content.IndexOf($marker); if($hrefStart -lt 0){ Write-Host '未在 USTC LatestRelease 页面中找到 Git 64 位安装包链接。' -ForegroundColor Yellow; $debugFile=Join-Path $env:TEMP 'wq-ustc-latestrelease.html'; $content | Set-Content -Path $debugFile -Encoding UTF8; Write-Host ('USTC LatestRelease 页面内容已保存到: ' + $debugFile) -ForegroundColor Yellow; exit 1 }; $hrefStart=$hrefStart + $marker.Length; $quote=[char]34; $hrefEnd=$content.IndexOf($quote,$hrefStart); if($hrefEnd -lt 0){ Write-Host '未在 USTC LatestRelease 页面中找到 Git 64 位安装包链接（未找到结束引号）。' -ForegroundColor Yellow; $debugFile=Join-Path $env:TEMP 'wq-ustc-latestrelease.html'; $content | Set-Content -Path $debugFile -Encoding UTF8; Write-Host ('USTC LatestRelease 页面内容已保存到: ' + $debugFile) -ForegroundColor Yellow; exit 1 }; $fullPath=$content.Substring($hrefStart,$hrefEnd-$hrefStart); $file=[System.IO.Path]::GetFileName($fullPath); $url=$base + $file; $url | Set-Content -Encoding ASCII '%GIT_URL_FILE%'; exit 0 } catch { Write-Host '获取 USTC Git LatestRelease 页面失败：' -ForegroundColor Yellow; if ($_.Exception) { Write-Host $_.Exception.Message -ForegroundColor Red; if ($_.Exception.Response -and $_.Exception.Response.StatusCode) { Write-Host ('HTTP 状态码: ' + [int]$_.Exception.Response.StatusCode) -ForegroundColor Red } } exit 1 }"
    if errorlevel 1 (
        del /f /q "%GIT_URL_FILE%" >nul 2>&1
        echo "从 USTC 镜像解析最新版本失败，将尝试从 SDU 镜像解析..."
        powershell -NoProfile -Command "$ProgressPreference='SilentlyContinue'; $base='%GIT_SDU_LIST_URL%'; $headers=@{ 'User-Agent'='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0'; 'Accept'='text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'; 'Accept-Language'='zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5'; 'Referer'=$base; 'Cache-Control'='no-cache'; 'Pragma'='no-cache' }; try { $response=Invoke-WebRequest -UseBasicParsing -Uri $base -Headers $headers; $content=$response.Content; $m=[regex]::Match($content,'v([0-9\\.]+)\\.windows\\.1/'); if(-not $m.Success){ Write-Host '未在 SDU 镜像页面中找到 Git 版本目录，将使用默认版本 2.52.0。' -ForegroundColor Yellow; $debugFile=Join-Path $env:TEMP 'wq-sdu-list.html'; $content | Set-Content -Path $debugFile -Encoding UTF8; Write-Host ('SDU Git 镜像页面内容已保存到: ' + $debugFile) -ForegroundColor Yellow; exit 1 }; $version=$m.Groups[1].Value; $file='Git-' + $version + '-64-bit.exe'; $url=$base + 'v' + $version + '.windows.1/' + $file; $url | Set-Content -Encoding ASCII '%GIT_URL_FILE%'; exit 0 } catch { Write-Host '获取 SDU Git 镜像页面失败，将使用默认版本 2.52.0：' -ForegroundColor Yellow; if ($_.Exception) { Write-Host $_.Exception.Message -ForegroundColor Red; if ($_.Exception.Response -and $_.Exception.Response.StatusCode) { Write-Host ('HTTP 状态码: ' + [int]$_.Exception.Response.StatusCode) -ForegroundColor Red } } exit 1 }"
        if errorlevel 1 (
            del /f /q "%GIT_URL_FILE%" >nul 2>&1
            echo "Git 最新版本解析失败，将尝试使用各镜像默认版本 Git 2.52.0。"
            set "GIT_INSTALLER_URL=%GIT_SDU_FALLBACK_URL%"
        ) else (
            if exist "%GIT_URL_FILE%" (
                set /p GIT_INSTALLER_URL=<"%GIT_URL_FILE%"
            )
            del /f /q "%GIT_URL_FILE%" >nul 2>&1
            if "%GIT_INSTALLER_URL%"=="" (
                echo "Git 最新版本解析结果为空，将尝试使用各镜像默认版本 Git 2.52.0。"
                set "GIT_INSTALLER_URL=%GIT_SDU_FALLBACK_URL%"
            )
        )
    ) else (
        if exist "%GIT_URL_FILE%" (
            set /p GIT_INSTALLER_URL=<"%GIT_URL_FILE%"
        )
        del /f /q "%GIT_URL_FILE%" >nul 2>&1
        if "%GIT_INSTALLER_URL%"=="" (
            echo "Git 最新版本解析结果为空，将尝试使用 USTC 默认版本 Git 2.52.0。"
            set "GIT_INSTALLER_URL=%GIT_USTC_FALLBACK_URL%"
        )
    )
) else (
    if exist "%GIT_URL_FILE%" (
        set /p GIT_INSTALLER_URL=<"%GIT_URL_FILE%"
    )
    del /f /q "%GIT_URL_FILE%" >nul 2>&1
    if "%GIT_INSTALLER_URL%"=="" (
        echo "Git 最新版本解析结果为空，将尝试使用 NJU 默认版本 Git 2.52.0。"
        set "GIT_INSTALLER_URL=%GIT_NJU_FALLBACK_URL%"
    )
)

if "%GIT_INSTALLER_URL%"=="" (
    echo "无法自动获取 Git 下载地址，请稍后手动安装 Git。"
    goto :eof
)

echo "Git 下载地址已确定为: %GIT_INSTALLER_URL%"

set "GIT_INSTALLER=%TEMP%\Git-Installer.exe"
set "GIT_TUNA_URL=%GIT_INSTALLER_URL%"
set "GIT_TUNA_URL=!GIT_TUNA_URL:mirrors.sdu.edu.cn/github-release/git-for-windows_git/=mirror.tuna.tsinghua.edu.cn/github-release/git-for-windows/git/!"
if "%GIT_TUNA_URL%"=="" (
    set "GIT_TUNA_URL=%GIT_TUNA_FALLBACK_URL%"
)

echo "正在尝试从清华 TUNA 镜像下载 Git..."
powershell -NoProfile -Command "$ProgressPreference='SilentlyContinue'; $headers=@{ 'User-Agent'='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0'; 'Accept'='*/*'; 'Accept-Language'='zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5'; 'Referer'='%GIT_TUNA_URL%'; 'Cache-Control'='no-cache'; 'Pragma'='no-cache' }; try { Invoke-WebRequest -Uri '%GIT_TUNA_URL%' -OutFile '%GIT_INSTALLER%' -UseBasicParsing -Headers $headers; exit 0 } catch { Write-Host '从清华 TUNA 镜像下载 Git 失败，将尝试从 SDU 镜像下载。' -ForegroundColor Yellow; if ($_.Exception) { Write-Host $_.Exception.Message -ForegroundColor Red; if ($_.Exception.Response -and $_.Exception.Response.StatusCode) { Write-Host ('HTTP 状态码: ' + [int]$_.Exception.Response.StatusCode) -ForegroundColor Red } } exit 1 }"
if errorlevel 1 (
    echo "正在从 SDU 镜像下载 Git..."
    powershell -NoProfile -Command "$ProgressPreference='SilentlyContinue'; $headers=@{ 'User-Agent'='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0'; 'Accept'='*/*'; 'Accept-Language'='zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5'; 'Referer'='%GIT_INSTALLER_URL%'; 'Cache-Control'='no-cache'; 'Pragma'='no-cache' }; try { Invoke-WebRequest -Uri '%GIT_INSTALLER_URL%' -OutFile '%GIT_INSTALLER%' -UseBasicParsing -Headers $headers; exit 0 } catch { Write-Host '从 SDU 镜像下载 Git 失败。' -ForegroundColor Yellow; if ($_.Exception) { Write-Host $_.Exception.Message -ForegroundColor Red; if ($_.Exception.Response -and $_.Exception.Response.StatusCode) { Write-Host ('HTTP 状态码: ' + [int]$_.Exception.Response.StatusCode) -ForegroundColor Red } } exit 1 }"
    if errorlevel 1 (
        echo "Git 安装包下载失败，请检查网络，或手动访问以下链接下载安装："
        echo "  %GIT_TUNA_URL%"
        echo "  %GIT_INSTALLER_URL%"
        echo "你也可以访问以下 Git 列表页面自行下载最新版本："
        echo "  %GIT_NJU_LIST_URL%"
        echo "  %GIT_USTC_LIST_URL%"
        echo "  %GIT_SDU_LIST_URL%"
        echo "  %GIT_TUNA_LIST_URL%"
        goto :eof
    )
)

echo "正在静默安装 Git..."
start "" /wait "%GIT_INSTALLER%" /VERYSILENT /NORESTART /NOCANCEL /SP- /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS
if errorlevel 1 (
    echo "Git 安装过程出现错误，请尝试手动运行安装包："
    echo "  %GIT_INSTALLER%"
    goto :eof
)

del /f /q "%GIT_INSTALLER%" >nul 2>&1

where git >nul 2>&1
if %errorlevel%==0 (
    git --version
    echo "Git 安装完成！"
) else (
    echo "已执行 Git 安装，但当前会话未检测到 git 命令；请重新打开终端后再运行 git --version 检查。"
)
goto :eof


:ConfigWindowsTerminalContextMenu
if /I "%USE_POWERSHELL_MENU%"=="1" (
    echo "未检测到 Windows Terminal，将使用 PowerShell 配置资源管理器右键菜单..."
    set "WT_EXE="
    for /f "delims=" %%I in ('where powershell') do (
        set "WT_EXE=%%I"
        goto :ConfigWtPathDone
    )
) else (
    echo "检测到 Windows Terminal，正在配置资源管理器右键菜单“在此处打开 Windows Terminal”..."
    set "WT_EXE="
    for /f "delims=" %%I in ('where wt.exe') do (
        set "WT_EXE=%%I"
        goto :ConfigWtPathDone
    )
)

:ConfigWtPathDone
if "%WT_EXE%"=="" (
    if /I "%USE_POWERSHELL_MENU%"=="1" (
        set "WT_EXE=powershell.exe"
    ) else (
        set "WT_EXE=wt.exe"
    )
)

if /I "%USE_POWERSHELL_MENU%"=="1" (
    set "BASE_MENU_TEXT=在此处打开 PowerShell"
) else (
    set "BASE_MENU_TEXT=在此处打开 Windows Terminal"
)

set "WT_DIR_MENU=HKCR\Directory\shell\OpenWindowsTerminalHere"
set "WT_BG_MENU=HKCR\Directory\Background\shell\OpenWindowsTerminalHere"
set "WT_DIR_MENU_CODEX=HKCR\Directory\shell\OpenTerminalHereWithCodex"
set "WT_BG_MENU_CODEX=HKCR\Directory\Background\shell\OpenTerminalHereWithCodex"
set "WT_DIR_MENU_CLAUDE=HKCR\Directory\shell\OpenTerminalHereWithClaudeCode"
set "WT_BG_MENU_CLAUDE=HKCR\Directory\Background\shell\OpenTerminalHereWithClaudeCode"
set "WT_DIR_MENU_GEMINI=HKCR\Directory\shell\OpenTerminalHereWithGemini"
set "WT_BG_MENU_GEMINI=HKCR\Directory\Background\shell\OpenTerminalHereWithGemini"
set "WT_DIR_MENU_CODEX_FREE=HKCR\Directory\shell\OpenTerminalHereWithCodexFree"
set "WT_BG_MENU_CODEX_FREE=HKCR\Directory\Background\shell\OpenTerminalHereWithCodexFree"
set "WT_DIR_MENU_CLAUDE_FREE=HKCR\Directory\shell\OpenTerminalHereWithClaudeFree"
set "WT_BG_MENU_CLAUDE_FREE=HKCR\Directory\Background\shell\OpenTerminalHereWithClaudeFree"
set "WT_DIR_MENU_GEMINI_FREE=HKCR\Directory\shell\OpenTerminalHereWithGeminiFree"
set "WT_BG_MENU_GEMINI_FREE=HKCR\Directory\Background\shell\OpenTerminalHereWithGeminiFree"

set "ADD_WT_MENU="
set /p ADD_WT_MENU=是否为资源管理器添加基础“%BASE_MENU_TEXT%”右键菜单? ^(Y/N, 默认 Y^): 
if /I "%ADD_WT_MENU%"=="N" (
    echo "已跳过添加基础终端右键菜单。"
) else (
    if /I "%USE_POWERSHELL_MENU%"=="1" (
        reg add "%WT_DIR_MENU%" /ve /d "%BASE_MENU_TEXT%" /f >nul 2>&1
        reg add "%WT_DIR_MENU%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'\"" /f >nul 2>&1

        reg add "%WT_BG_MENU%" /ve /d "%BASE_MENU_TEXT%" /f >nul 2>&1
        reg add "%WT_BG_MENU%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'\"" /f >nul 2>&1
    ) else (
        reg add "%WT_DIR_MENU%" /ve /d "%BASE_MENU_TEXT%" /f >nul 2>&1
        reg add "%WT_DIR_MENU%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\"" /f >nul 2>&1

        reg add "%WT_BG_MENU%" /ve /d "%BASE_MENU_TEXT%" /f >nul 2>&1
        reg add "%WT_BG_MENU%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\"" /f >nul 2>&1
    )
)

set "ADD_CLI_MENU="
set /p ADD_CLI_MENU=是否为资源管理器添加“在此处打开 Terminal 并启动 Codex/Claude/Gemini”右键菜单? ^(Y/N, 默认 Y^): 
if /I "%ADD_CLI_MENU%"=="N" (
    echo "已跳过添加 CLI 启动类右键菜单。"
) else (
    if /I "%USE_POWERSHELL_MENU%"=="1" (
        reg add "%WT_DIR_MENU_CODEX%" /ve /d "在此处打开 Terminal 并启动codex" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CODEX%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CODEX%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; codex\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_CODEX%" /ve /d "在此处打开 Terminal 并启动codex" /f >nul 2>&1
        reg add "%WT_BG_MENU_CODEX%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; codex\"" /f >nul 2>&1

        reg add "%WT_DIR_MENU_CLAUDE%" /ve /d "在此处打开 Terminal 并启动claude" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CLAUDE%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CLAUDE%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; claude\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_CLAUDE%" /ve /d "在此处打开 Terminal 并启动claude" /f >nul 2>&1
        reg add "%WT_BG_MENU_CLAUDE%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; claude\"" /f >nul 2>&1

        reg add "%WT_DIR_MENU_GEMINI%" /ve /d "在此处打开 Terminal 并启动gemini" /f >nul 2>&1
        reg add "%WT_DIR_MENU_GEMINI%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_GEMINI%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; gemini\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_GEMINI%" /ve /d "在此处打开 Terminal 并启动gemini" /f >nul 2>&1
        reg add "%WT_BG_MENU_GEMINI%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; gemini\"" /f >nul 2>&1
    ) else (
        reg add "%WT_DIR_MENU_CODEX%" /ve /d "在此处打开 Terminal 并启动codex" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CODEX%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CODEX%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"codex\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_CODEX%" /ve /d "在此处打开 Terminal 并启动codex" /f >nul 2>&1
        reg add "%WT_BG_MENU_CODEX%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"codex\"" /f >nul 2>&1

        reg add "%WT_DIR_MENU_CLAUDE%" /ve /d "在此处打开 Terminal 并启动claude" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CLAUDE%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CLAUDE%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"claude\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_CLAUDE%" /ve /d "在此处打开 Terminal 并启动claude" /f >nul 2>&1
        reg add "%WT_BG_MENU_CLAUDE%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"claude\"" /f >nul 2>&1

        reg add "%WT_DIR_MENU_GEMINI%" /ve /d "在此处打开 Terminal 并启动gemini" /f >nul 2>&1
        reg add "%WT_DIR_MENU_GEMINI%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_GEMINI%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"gemini\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_GEMINI%" /ve /d "在此处打开 Terminal 并启动gemini" /f >nul 2>&1
        reg add "%WT_BG_MENU_GEMINI%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"gemini\"" /f >nul 2>&1
    )
)

set "ADD_CLI_FREE_MENU="
set /p ADD_CLI_FREE_MENU=是否为资源管理器添加“在此处打开 Terminal 并启动 Codex/Claude/Gemini 自由AI模式”右键菜单? ^(Y/N, 默认 Y^): 
if /I "%ADD_CLI_FREE_MENU%"=="N" (
    echo "已跳过添加 CLI 自由AI模式右键菜单。"
) else (
    if /I "%USE_POWERSHELL_MENU%"=="1" (
        reg add "%WT_DIR_MENU_CODEX_FREE%" /ve /d "在此处打开 Terminal 并启动codex（自由AI）" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CODEX_FREE%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CODEX_FREE%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; codex --dangerously-bypass-approvals-and-sandbox\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_CODEX_FREE%" /ve /d "在此处打开 Terminal 并启动codex（自由AI）" /f >nul 2>&1
        reg add "%WT_BG_MENU_CODEX_FREE%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; codex --dangerously-bypass-approvals-and-sandbox\"" /f >nul 2>&1

        reg add "%WT_DIR_MENU_CLAUDE_FREE%" /ve /d "在此处打开 Terminal 并启动claude（自由AI）" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CLAUDE_FREE%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CLAUDE_FREE%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; claude --dangerously-skip-permissions\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_CLAUDE_FREE%" /ve /d "在此处打开 Terminal 并启动claude（自由AI）" /f >nul 2>&1
        reg add "%WT_BG_MENU_CLAUDE_FREE%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; claude --dangerously-skip-permissions\"" /f >nul 2>&1

        reg add "%WT_DIR_MENU_GEMINI_FREE%" /ve /d "在此处打开 Terminal 并启动gemini（自由AI）" /f >nul 2>&1
        reg add "%WT_DIR_MENU_GEMINI_FREE%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_GEMINI_FREE%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; gemini -y\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_GEMINI_FREE%" /ve /d "在此处打开 Terminal 并启动gemini（自由AI）" /f >nul 2>&1
        reg add "%WT_BG_MENU_GEMINI_FREE%\command" /ve /d "\"%WT_EXE%\" -NoExit -Command \"Set-Location -LiteralPath '%%V'; gemini -y\"" /f >nul 2>&1
    ) else (
        reg add "%WT_DIR_MENU_CODEX_FREE%" /ve /d "在此处打开 Terminal 并启动codex（自由AI）" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CODEX_FREE%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CODEX_FREE%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"codex --dangerously-bypass-approvals-and-sandbox\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_CODEX_FREE%" /ve /d "在此处打开 Terminal 并启动codex（自由AI）" /f >nul 2>&1
        reg add "%WT_BG_MENU_CODEX_FREE%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"codex --dangerously-bypass-approvals-and-sandbox\"" /f >nul 2>&1

        reg add "%WT_DIR_MENU_CLAUDE_FREE%" /ve /d "在此处打开 Terminal 并启动claude（自由AI）" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CLAUDE_FREE%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_CLAUDE_FREE%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"claude --dangerously-skip-permissions\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_CLAUDE_FREE%" /ve /d "在此处打开 Terminal 并启动claude（自由AI）" /f >nul 2>&1
        reg add "%WT_BG_MENU_CLAUDE_FREE%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"claude --dangerously-skip-permissions\"" /f >nul 2>&1

        reg add "%WT_DIR_MENU_GEMINI_FREE%" /ve /d "在此处打开 Terminal 并启动gemini（自由AI）" /f >nul 2>&1
        reg add "%WT_DIR_MENU_GEMINI_FREE%" /v "Icon" /d "%WT_EXE%" /f >nul 2>&1
        reg add "%WT_DIR_MENU_GEMINI_FREE%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"gemini -y\"" /f >nul 2>&1

        reg add "%WT_BG_MENU_GEMINI_FREE%" /ve /d "在此处打开 Terminal 并启动gemini（自由AI）" /f >nul 2>&1
        reg add "%WT_BG_MENU_GEMINI_FREE%\command" /ve /d "\"%WT_EXE%\" -d \"%%V\" powershell -NoExit -Command \"gemini -y\"" /f >nul 2>&1
    )
)

echo "Windows Terminal 右键菜单配置步骤已完成。"
goto :eof


:EnsureNodeNpm
set "NODE_AVAILABLE=0"
echo.
echo "[2/8] 检查/安装 Node.js..."

REM 先尝试将常见 Node.js 和 npm 路径加入当前会话 PATH，确保后续检测有效
if defined ProgramFiles (
    set "PATH=%ProgramFiles%\nodejs;%PATH%"
)
if defined ProgramFiles(x86) (
    set "PATH=%ProgramFiles(x86)%\nodejs;%PATH%"
)
if not "%APPDATA%"=="" (
    set "PATH=%APPDATA%\npm;%PATH%"
)

where node.exe >nul 2>&1
if %errorlevel%==0 (
    echo "Node.js 已安装，跳过自动安装。"
    goto EnsureNpmPath
)

echo "未检测到 Node.js (node.exe)，将从官方地址下载安装 Node.js (x64)..."

set "NODE_MSI=%TEMP%\node-x64.msi"
echo "下载地址: %NODE_INSTALLER_URL%"
echo "下载到: %NODE_MSI%"

powershell -NoProfile -Command "$ProgressPreference='SilentlyContinue'; try { Invoke-WebRequest -Uri '%NODE_INSTALLER_URL%' -OutFile '%NODE_MSI%' -UseBasicParsing; exit 0 } catch { Write-Host 'Node.js 安装包下载失败：' -ForegroundColor Yellow; if ($_.Exception) { Write-Host $_.Exception.Message -ForegroundColor Red; if ($_.Exception.Response -and $_.Exception.Response.StatusCode) { Write-Host ('HTTP 状态码: ' + [int]$_.Exception.Response.StatusCode) -ForegroundColor Red } } exit 1 }"
if errorlevel 1 (
    echo "Node.js 安装包下载失败，请检查网络，或手动访问以下链接下载安装："
    echo "  %NODE_INSTALLER_URL%"
    goto :eof
)

echo "正在静默安装 Node.js (这可能需要一点时间)..."
msiexec /i "%NODE_MSI%" /qn /norestart
if errorlevel 1 (
    echo "Node.js 安装过程出现错误，请尝试手动运行安装包："
    echo "  %NODE_MSI%"
    goto :eof
)

where node.exe >nul 2>&1
if %errorlevel% neq 0 (
    echo "安装完成后仍未检测到 node.exe，请检查 Node.js 安装目录或重新打开终端后再次运行本脚本。"
    goto :eof
)

echo "Node.js 安装完成。"
goto EnsureNpmPath

:EnsureNpmPath
REM 尝试将常见 Node.js 和 npm 路径加入当前会话 PATH
if defined ProgramFiles (
    set "PATH=%ProgramFiles%\nodejs;%PATH%"
)
if defined ProgramFiles(x86) (
    set "PATH=%ProgramFiles(x86)%\nodejs;%PATH%"
)
if not "%APPDATA%"=="" (
    set "PATH=%APPDATA%\npm;%PATH%"
)

where npm >nul 2>&1
if %errorlevel% neq 0 (
    echo "Node.js 安装似乎未生效，请检查安装输出与 PATH 设置；"
    echo "如仍有问题，可重启终端后再次运行此脚本。"
    goto :eof
)

set "NODE_AVAILABLE=1"
goto :eof


:ConfigNpmMirror
echo.
echo "[3/8] 配置 npm 淘宝镜像 (npmmirror)..."
REM 移除旧的代理设置（防止冲突）
cmd /c "npm config delete proxy" >nul 2>&1
cmd /c "npm config delete https-proxy" >nul 2>&1

REM 移除可能的 scope 专用源配置，确保统一走 npmmirror
cmd /c "npm config delete @anthropic-ai:registry" >nul 2>&1
cmd /c "npm config delete @openai:registry" >nul 2>&1
cmd /c "npm config delete @google:registry" >nul 2>&1

REM 设置新版淘宝镜像为全局默认源
cmd /c "npm config set registry https://registry.npmmirror.com"
for /f "delims=" %%A in ('npm config get registry') do set "NPM_REGISTRY=%%A"
echo "当前 npm 源: %NPM_REGISTRY%"
goto :eof


:ConfigTokens
echo.
echo "[8/8] 配置 API Base 与各 CLI 的 Token (API Key)..."
set "API_BASE="
set /p API_BASE=请输入 API Base URL ^(留空使用默认 https://api.share-ai.woolen.wang^)： 
if "%API_BASE%"=="" (
    set "API_BASE=https://api.share-ai.woolen.wang"
)

echo "[8/8] 配置各 CLI 的 Token (API Key)..."
set "API_KEY="
set /p API_KEY=请输入 ShareAI API Token ^(例如 sk-xxxx^)，留空则仅安装 CLI 而不配置 Token: 

if "%API_KEY%"=="" (
    echo "未输入 Token，本次仅完成 CLI 安装，未配置任何 Token 或配置文件。"
    goto :eof
)

REM 配置 Claude / Codex / Gemini 的环境变量（持久和当前会话）
setx ANTHROPIC_BASE_URL "%API_BASE%" >nul
@REM setx ANTHROPIC_API_KEY "%API_KEY%" >nul
setx ANTHROPIC_AUTH_TOKEN "%API_KEY%" >nul
setx CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC "1" >nul
setx OPENAI_BASE_URL "%API_BASE%" >nul
setx OPENAI_API_KEY "%API_KEY%" >nul
setx CODE_ASSIST_ENDPOINT "%API_BASE%" >nul
setx GEMINI_API_KEY "%API_KEY%" >nul
setx GOOGLE_GEMINI_BASE_URL "%API_BASE%" >nul
setx GOOGLE_GENAI_USE_GCA "true" >nul

set "ANTHROPIC_BASE_URL=%API_BASE%"
set "ANTHROPIC_AUTH_TOKEN=%API_KEY%"
set "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1"
set "OPENAI_BASE_URL=%API_BASE%"
set "OPENAI_API_KEY=%API_KEY%"
set "CODE_ASSIST_ENDPOINT=%API_BASE%"
set "GEMINI_API_KEY=%API_KEY%"
set "GOOGLE_GEMINI_BASE_URL=%API_BASE%"
set "GOOGLE_GENAI_USE_GCA=true"

call :WriteClaudeConfig
call :WriteCodexConfig
call :WriteGeminiConfig
call :WriteOpenClawConfig

echo "Token 和配置文件已为 Claude Code / Codex / Gemini 统一配置完成（如已安装）。"
echo "注意: 新的环境变量在重新打开 PowerShell 或 CMD 后生效。"

REM Droid CLI 的自定义模型配置较复杂，如有需要可在 .factory/config.json 中手动配置。
goto :eof


:WriteClaudeConfig
if "%USERPROFILE%"=="" (
    echo "无法确定用户主目录，跳过 Claude Code 配置文件写入。"
    goto :eof
)

set "CLAUDE_DIR=%USERPROFILE%\.claude"
if not exist "%CLAUDE_DIR%" (
    mkdir "%CLAUDE_DIR%"
)

set "CLAUDE_SETTINGS=%CLAUDE_DIR%\settings.json"
if exist "%CLAUDE_SETTINGS%" (
    for %%A in ("%CLAUDE_SETTINGS%") do if %%~zA GTR 0 (
        findstr /C:"ANTHROPIC_BASE_URL" "%CLAUDE_SETTINGS%" >nul 2>&1
        if not errorlevel 1 (
            echo "检测到已有 Claude Code 配置文件且已包含 ANTHROPIC_BASE_URL: %CLAUDE_SETTINGS%"
        ) else (
            echo "检测到已有 Claude Code 配置文件，但未检测到关键字段 ANTHROPIC_BASE_URL: %CLAUDE_SETTINGS%"
        )
        set "OVERWRITE_CLAUDE="
        set /p OVERWRITE_CLAUDE=是否覆盖该 Claude Code 配置文件? ^(Y/N, 默认 N^): 
        if /I not "!OVERWRITE_CLAUDE!"=="Y" (
            echo "保留原有 Claude Code 配置文件，跳过自动写入。"
            goto :eof
        )
    )
)

> "%CLAUDE_SETTINGS%" (
    echo {
    echo   "env": {
    echo     "ANTHROPIC_AUTH_TOKEN": "%API_KEY%",
    echo     "ANTHROPIC_BASE_URL": "%API_BASE%",
    echo     "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"
    echo   },
    echo   "statusLine": {
    echo     "type": "command",
    echo     "command": "npx -y ccstatusline@latest",
    echo     "padding": 0
    echo   },
    echo   "permissions": {
    echo     "allow": [],
    echo     "deny": []
    echo   }
    echo }
)

echo "已写入 Claude Code 配置文件: %CLAUDE_SETTINGS%"
goto :eof


:WriteCodexConfig
if "%USERPROFILE%"=="" (
    echo "无法确定用户主目录，跳过 Codex CLI 配置文件写入。"
    goto :eof
)

set "CODEX_DIR=%USERPROFILE%\.codex"
if not exist "%CODEX_DIR%" (
    mkdir "%CODEX_DIR%"
)

set "CODEX_CONFIG=%CODEX_DIR%\config.toml"
set "CODEX_AUTH=%CODEX_DIR%\auth.json"

if exist "%CODEX_CONFIG%" (
    for %%A in ("%CODEX_CONFIG%") do if %%~zA GTR 0 (
        findstr /C:"base_url" "%CODEX_CONFIG%" >nul 2>&1
        if not errorlevel 1 (
            echo "检测到已有 Codex CLI 配置文件且已包含 base_url: %CODEX_CONFIG%"
        ) else (
            echo "检测到已有 Codex CLI 配置文件，但未检测到关键字段 base_url: %CODEX_CONFIG%"
        )
        set "OVERWRITE_CODEX="
        set /p OVERWRITE_CODEX=是否覆盖该 Codex CLI 配置文件? ^(Y/N, 默认 N^): 
        if /I not "!OVERWRITE_CODEX!"=="Y" (
            echo "保留原有 Codex CLI 配置文件，跳过自动写入。"
            goto :eof
        )
    )
)

> "%CODEX_CONFIG%" (
    echo disable_response_storage = true
    echo model = "gpt-5.2"
    echo model_reasoning_effort = "high"
    echo model_provider = "share-ai"
    echo sandbox_mode = "danger-full-access"
    echo windows_wsl_setup_acknowledged = true
    echo base_instructions = "Always prefer built-in tools (read_file, list_dir, grep_files) over shell commands for file operations."
    echo.
    echo [experimental]
    echo use_freeform_apply_patch = true
    echo use_unified_exec_tool = true
    echo.
    echo [features]
    echo apply_patch_freeform = true
    echo ghost_commit = true
    echo plan_tool = true
    echo rmcp_client = true
    echo streamable_shell = false
    echo unified_exec = false
    echo view_image_tool = true
    echo web_search_request = true
    echo enable_experimental_windows_sandbox = true
    echo experimental_sandbox_command_assessment = true
    echo parallel = true
    echo.
    echo [model_providers.share-ai]
    echo base_url = "%API_BASE%/v1"
    echo name = "share-ai"
    echo requires_openai_auth = true
    echo wire_api = "responses"
    echo.
    echo [sandbox_workspace_write]
    echo network_access = true
)

> "%CODEX_AUTH%" (
    echo {
    echo   "OPENAI_API_KEY": "%API_KEY%"
    echo }
)

echo "已写入 Codex CLI 配置文件: %CODEX_CONFIG%"
echo "已写入 Codex CLI 认证文件: %CODEX_AUTH%"
goto :eof


:WriteGeminiConfig
if "%USERPROFILE%"=="" (
    echo "无法确定用户主目录，跳过 Gemini CLI 配置文件写入。"
    goto :eof
)

set "GEMINI_DIR=%USERPROFILE%\.gemini"
if not exist "%GEMINI_DIR%" (
    mkdir "%GEMINI_DIR%"
)

set "GEMINI_ENV=%GEMINI_DIR%\.env"
if exist "%GEMINI_ENV%" (
    for %%A in ("%GEMINI_ENV%") do if %%~zA GTR 0 (
        findstr /C:"GEMINI_API_BASE_URL" "%GEMINI_ENV%" >nul 2>&1
        if not errorlevel 1 (
            echo "检测到已有 Gemini CLI 配置文件且已包含 GEMINI_API_BASE_URL: %GEMINI_ENV%"
        ) else (
            echo "检测到已有 Gemini CLI 配置文件，但未检测到关键字段 GEMINI_API_BASE_URL: %GEMINI_ENV%"
        )
        set "OVERWRITE_GEMINI="
        set /p OVERWRITE_GEMINI=是否覆盖该 Gemini CLI 配置文件? ^(Y/N, 默认 N^): 
        if /I not "!OVERWRITE_GEMINI!"=="Y" (
            echo "保留原有 Gemini CLI 配置文件，跳过自动写入。"
            goto :eof
        )
    )
)

> "%GEMINI_ENV%" (
    echo GEMINI_API_KEY=%API_KEY%
    echo GOOGLE_GEMINI_BASE_URL=%API_BASE%
)

set "GEMINI_SETTINGS=%GEMINI_DIR%\settings.json"
> "%GEMINI_SETTINGS%" (
    echo {
    echo   "security": {
    echo     "auth": {
    echo       "selectedType": "gemini-api-key"
    echo     },
    echo     "folderTrust": {
    echo       "enabled": true
    echo     }
    echo   }
    echo }
)

echo "已写入 Gemini CLI 环境变量文件: %GEMINI_ENV%"
echo "已写入 Gemini CLI 配置文件: %GEMINI_SETTINGS%"
set "GEMINI_INSTALL_ID_FILE=%GEMINI_DIR%\installation_id"
set "GEMINI_INSTALL_ID="

if exist "%GEMINI_INSTALL_ID_FILE%" (
    for /f "usebackq delims=" %%G in ("%GEMINI_INSTALL_ID_FILE%") do set "GEMINI_INSTALL_ID=%%G"
)

if "!GEMINI_INSTALL_ID!"=="" (
    for /f "delims=" %%G in ('powershell -NoProfile -Command "[guid]::NewGuid().ToString()"') do set "GEMINI_INSTALL_ID=%%G"
    if not "!GEMINI_INSTALL_ID!"=="" (
        > "%GEMINI_INSTALL_ID_FILE%" echo !GEMINI_INSTALL_ID!
        echo "已生成 Gemini CLI 安装 ID: !GEMINI_INSTALL_ID!"
    ) else (
        echo "生成 Gemini CLI 安装 ID 失败。"
    )
) else (
    echo "检测到已有 Gemini CLI 安装 ID 文件: %GEMINI_INSTALL_ID_FILE%"
)
goto :eof


:WriteOpenClawConfig
if "%USERPROFILE%"=="" (
    echo "无法确定用户主目录，跳过 OpenClaw 配置文件写入。"
    goto :eof
)

where openclaw >nul 2>&1
if %errorlevel% neq 0 (
    echo "未检测到 OpenClaw CLI，跳过 OpenClaw 配置文件写入。"
    goto :eof
)

set "OPENCLAW_DIR=%USERPROFILE%\.openclaw"
if not exist "%OPENCLAW_DIR%" (
    mkdir "%OPENCLAW_DIR%"
)

set "OPENCLAW_CONFIG=%OPENCLAW_DIR%\openclaw.json"
if exist "%OPENCLAW_CONFIG%" (
    for %%A in ("%OPENCLAW_CONFIG%") do if %%~zA GTR 0 (
        findstr /C:"shareai" "%OPENCLAW_CONFIG%" >nul 2>&1
        if not errorlevel 1 (
            echo "检测到已有 OpenClaw 配置文件且已包含 shareai 配置: %OPENCLAW_CONFIG%"
        ) else (
            echo "检测到已有 OpenClaw 配置文件: %OPENCLAW_CONFIG%"
        )
        set "OVERWRITE_OPENCLAW="
        set /p OVERWRITE_OPENCLAW=是否覆盖该 OpenClaw 配置文件? ^(Y/N, 默认 N^):
        if /I not "!OVERWRITE_OPENCLAW!"=="Y" (
            echo "保留原有 OpenClaw 配置文件，跳过自动写入。"
            goto :eof
        )
    )
)

REM 生成当前 UTC 时间戳
set "NOW_TS="
for /f "delims=" %%T in ('powershell -NoProfile -Command "[DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ss.fffZ')"') do set "NOW_TS=%%T"
if "!NOW_TS!"=="" set "NOW_TS=2026-01-01T00:00:00.000Z"

REM 生成随机 Gateway Token
set "GW_TOKEN="
for /f "delims=" %%T in ('powershell -NoProfile -Command "([guid]::NewGuid().ToString('N')+[guid]::NewGuid().ToString('N')).Substring(0,48)"') do set "GW_TOKEN=%%T"
if "!GW_TOKEN!"=="" set "GW_TOKEN=000000000000000000000000000000000000000000000000"

REM 转换路径分隔符为正斜杠
set "HOME_FWD=!USERPROFILE:\=/!"

> "%OPENCLAW_CONFIG%" (
    echo {
    echo   "meta": {
    echo     "lastTouchedVersion": "2026.2.25",
    echo     "lastTouchedAt": "!NOW_TS!"
    echo   },
    echo   "wizard": {
    echo     "lastRunAt": "!NOW_TS!",
    echo     "lastRunVersion": "2026.2.6-3",
    echo     "lastRunCommand": "onboard",
    echo     "lastRunMode": "local"
    echo   },
    echo   "models": {
    echo     "mode": "merge",
    echo     "providers": {
    echo       "shareai-openai": {
    echo         "baseUrl": "%API_BASE%/v1",
    echo         "apiKey": "%API_KEY%",
    echo         "api": "openai-responses",
    echo         "models": [
    echo           {
    echo             "id": "gpt-5.2",
    echo             "name": "gpt-5.2",
    echo             "reasoning": true
    echo           },
    echo           {
    echo             "id": "gpt-5.3-codex",
    echo             "name": "gpt-5.3-codex",
    echo             "reasoning": true
    echo           },
    echo           {
    echo             "id": "gpt-5.4",
    echo             "name": "gpt-5.4",
    echo             "reasoning": true,
    echo             "input": ["text"],
    echo             "cost": {
    echo               "input": 0,
    echo               "output": 0,
    echo               "cacheRead": 0,
    echo               "cacheWrite": 0
    echo             },
    echo             "contextWindow": 1000000,
    echo             "maxTokens": 8192
    echo           }
    echo         ]
    echo       },
    echo       "shareai-claude": {
    echo         "baseUrl": "%API_BASE%/",
    echo         "apiKey": "%API_KEY%",
    echo         "api": "anthropic-messages",
    echo         "models": [
    echo           {
    echo             "id": "claude-opus-4-6",
    echo             "name": "claude-opus-4-6",
    echo             "reasoning": true,
    echo             "maxTokens": 8192
    echo           }
    echo         ]
    echo       }
    echo     }
    echo   },
    echo   "agents": {
    echo     "defaults": {
    echo       "model": {
    echo         "primary": "shareai-openai/gpt-5.4"
    echo       },
    echo       "workspace": "!HOME_FWD!/.openclaw/workspace",
    echo       "compaction": {
    echo         "reserveTokensFloor": 300000,
    echo         "memoryFlush": {
    echo           "enabled": true,
    echo           "softThresholdTokens": 20000
    echo         }
    echo       },
    echo       "timeoutSeconds": 1800,
    echo       "maxConcurrent": 10,
    echo       "subagents": {
    echo         "maxConcurrent": 20,
    echo         "maxSpawnDepth": 2,
    echo         "maxChildrenPerAgent": 5,
    echo         "runTimeoutSeconds": 900
    echo       }
    echo     }
    echo   },
    echo   "tools": {
    echo     "profile": "full"
    echo   },
    echo   "messages": {
    echo     "ackReactionScope": "group-mentions"
    echo   },
    echo   "commands": {
    echo     "native": "auto",
    echo     "nativeSkills": "auto",
    echo     "restart": true,
    echo     "ownerDisplay": "raw"
    echo   },
    echo   "skills": {
    echo     "install": {
    echo       "nodeManager": "npm"
    echo     }
    echo   },
    echo   "gateway": {
    echo     "port": 18789,
    echo     "mode": "local",
    echo     "bind": "loopback",
    echo     "auth": {
    echo       "mode": "token",
    echo       "token": "!GW_TOKEN!"
    echo     }
    echo   }
    echo }
)

echo "已写入 OpenClaw 配置文件: %OPENCLAW_CONFIG%"
goto :eof
