#!/bin/bash
# ==============================================================================
# WQuant AI CLI 工具一键安装脚本 (macOS版)
# 功能：自动安装 Node.js、Git 及四个 AI CLI 工具
# - Claude Code (Anthropic)
# - Codex CLI (OpenAI)
# - Gemini CLI (Google)
# - Droid CLI (Factory.ai)
# - OpenClaw
# ==============================================================================

set -e  # 遇到错误立即退出
set -u  # 使用未定义变量时报错

# ------------------------------------------------------------------------------
# 全局变量定义
# ------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
API_BASE="https://api.share-ai.woolen.wang"
NODE_VERSION="24.13.1"
NODE_MIRROR_BASE="https://registry.npmmirror.com/-/binary/node/v${NODE_VERSION}"
HOMEBREW_INSTALL_URL="https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh"
HOMEBREW_CN_MIRROR_URL="https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh"
export NODE_TLS_REJECT_UNAUTHORIZED=0
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# ------------------------------------------------------------------------------
# 工具函数
# ------------------------------------------------------------------------------

# 输出带颜色的信息
info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# 检测当前 Shell 类型
detect_shell_type() {
    if [ -n "${ZSH_VERSION:-}" ]; then
        echo "zsh"
    elif [ -n "${BASH_VERSION:-}" ]; then
        echo "bash"
    else
        echo "unknown"
    fi
}

# 获取 Shell 配置文件路径
get_shell_config() {
    local shell_type
    shell_type=$(detect_shell_type)

    if [ "$shell_type" = "zsh" ]; then
        echo "$HOME/.zshrc"
    elif [ "$shell_type" = "bash" ]; then
        if [ -f "$HOME/.bash_profile" ]; then
            echo "$HOME/.bash_profile"
        else
            echo "$HOME/.bashrc"
        fi
    else
        echo "$HOME/.profile"
    fi
}

# 请求用户确认
ask_confirmation() {
    local prompt="$1"
    local default="${2:-n}"
    local response

    if [ "$default" = "y" ] || [ "$default" = "Y" ]; then
        read -p "$prompt (Y/n): " -n 1 -r response
    else
        read -p "$prompt (y/N): " -n 1 -r response
    fi

    echo  # 换行

    # 如果用户直接回车，使用默认值
    if [ -z "$response" ]; then
        response="$default"
    fi

    if [[ "$response" =~ ^[Yy]$ ]]; then
        return 0
    else
        return 1
    fi
}

# 检查 sudo 权限
check_sudo_permission() {
    info "检查管理员权限..."

    if sudo -v; then
        success "管理员权限验证成功"
        # 保持 sudo 会话活跃
        while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &
        return 0
    else
        error "需要管理员权限才能继续安装"
        error "请输入管理员密码后重试"
        exit 1
    fi
}

# ------------------------------------------------------------------------------
# 阶段 1: 前置检查
# ------------------------------------------------------------------------------

check_prerequisites() {
    info "=== [1/9] 前置环境检查 ==="

    # 检查操作系统
    if [[ "$OSTYPE" != "darwin"* ]]; then
        error "此脚本仅支持 macOS 系统"
        exit 1
    fi

    # 检查 curl
    if ! command_exists curl; then
        error "未检测到 curl 命令，请先安装 Xcode Command Line Tools:"
        error "  xcode-select --install"
        exit 1
    fi

    success "前置检查完成"
}

# ------------------------------------------------------------------------------
# 阶段 2: Homebrew 安装
# ------------------------------------------------------------------------------

check_homebrew() {
    if command_exists brew; then
        success "检测到 Homebrew 已安装"
        return 0
    else
        return 1
    fi
}

install_homebrew() {
    info "=== [2/9] 安装 Homebrew 包管理器 ==="

    if check_homebrew; then
        return 0
    fi

    warning "未检测到 Homebrew，这是 macOS 上推荐的包管理工具"

    if ask_confirmation "是否安装 Homebrew？（强烈推荐）" "y"; then
        info "正在安装 Homebrew..."

        # 尝试国内镜像安装（更快）
        if ask_confirmation "是否使用国内镜像加速安装？" "y"; then
            info "使用国内镜像安装 Homebrew..."
            /bin/bash -c "$(curl -fsSL ${HOMEBREW_CN_MIRROR_URL})"
        else
            info "使用官方脚本安装 Homebrew..."
            /bin/bash -c "$(curl -fsSL ${HOMEBREW_INSTALL_URL})"
        fi

        # 添加 Homebrew 到 PATH (Apple Silicon Mac)
        if [[ $(uname -m) == "arm64" ]]; then
            info "检测到 Apple Silicon Mac，添加 Homebrew 到 PATH..."
            eval "$(/opt/homebrew/bin/brew shellenv)"

            # 写入 shell 配置文件
            local shell_config
            shell_config=$(get_shell_config)
            if ! grep -q "/opt/homebrew/bin/brew shellenv" "$shell_config" 2>/dev/null; then
                echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> "$shell_config"
            fi
        fi

        if check_homebrew; then
            success "Homebrew 安装成功"
        else
            error "Homebrew 安装失败，请手动访问 https://brew.sh 安装"
            return 1
        fi
    else
        warning "已跳过 Homebrew 安装，后续某些功能可能受限"
    fi
}

# ------------------------------------------------------------------------------
# 阶段 3: Node.js 安装
# ------------------------------------------------------------------------------

check_node_npm() {
    if command_exists node && command_exists npm; then
        local node_version
        node_version=$(node --version 2>/dev/null || echo "unknown")
        success "检测到 Node.js 已安装: ${node_version}"
        return 0
    else
        return 1
    fi
}

install_node_from_mirror() {
    info "=== [3/9] 安装 Node.js ==="

    if check_node_npm; then
        return 0
    fi

    info "未检测到 Node.js，准备安装..."

    # 优先尝试 Homebrew（如果可用）
    if command_exists brew && ask_confirmation "检测到 Homebrew，是否通过 Homebrew 安装 Node.js？（推荐）" "y"; then
        info "通过 Homebrew 安装 Node.js..."
        if brew install node; then
            success "Node.js 安装完成"
            return 0
        else
            warning "通过 Homebrew 安装失败，将尝试国内镜像"
        fi
    fi

    # 使用国内镜像下载 tar.gz
    info "使用国内镜像 (npmmirror) 下载 Node.js..."

    # 检测系统架构
    local arch
    arch=$(uname -m)
    local node_arch

    if [ "$arch" = "arm64" ]; then
        node_arch="darwin-arm64"
        info "检测到 Apple Silicon (ARM64) 架构"
    elif [ "$arch" = "x86_64" ]; then
        node_arch="darwin-x64"
        info "检测到 Intel (x64) 架构"
    else
        error "不支持的系统架构: $arch"
        return 1
    fi

    local node_filename="node-v${NODE_VERSION}-${node_arch}.tar.gz"
    local download_url="${NODE_MIRROR_BASE}/${node_filename}"
    local tmp_file="/tmp/${node_filename}"
    local tmp_dir="/tmp/node-install-$$"

    info "下载地址: ${download_url}"

    # 下载 Node.js
    if ! curl -L "${download_url}" -o "${tmp_file}"; then
        error "Node.js 下载失败，请检查网络连接"
        error "你也可以手动访问 https://nodejs.org 下载安装"
        return 1
    fi

    success "下载完成"

    # 解压到临时目录
    info "正在解压 Node.js..."
    mkdir -p "${tmp_dir}"
    tar -xzf "${tmp_file}" -C "${tmp_dir}"

    # 安装到 /usr/local
    local extracted_dir="${tmp_dir}/node-v${NODE_VERSION}-${node_arch}"

    if [ ! -d "${extracted_dir}" ]; then
        error "解压后的目录不存在: ${extracted_dir}"
        rm -rf "${tmp_dir}" "${tmp_file}"
        return 1
    fi

    info "正在安装 Node.js 到 /usr/local (需要管理员权限)..."

    # 复制文件到 /usr/local
    sudo cp -R "${extracted_dir}/bin/"* /usr/local/bin/
    sudo cp -R "${extracted_dir}/lib/"* /usr/local/lib/
    sudo cp -R "${extracted_dir}/include/"* /usr/local/include/
    sudo cp -R "${extracted_dir}/share/"* /usr/local/share/

    # 清理临时文件
    rm -rf "${tmp_dir}" "${tmp_file}"

    # 添加到当前会话的 PATH
    export PATH="/usr/local/bin:$PATH"

    # 验证安装
    if check_node_npm; then
        local installed_version
        installed_version=$(node --version)
        success "Node.js ${installed_version} 安装完成"
    else
        error "Node.js 安装后仍无法检测到，请关闭终端重新打开后再试"
        return 1
    fi
}

# ------------------------------------------------------------------------------
# 阶段 4: npm 镜像配置
# ------------------------------------------------------------------------------

configure_npm_mirror() {
    info "=== [4/9] 配置 npm 国内镜像 ==="

    if ! command_exists npm; then
        error "npm 不可用，无法配置镜像"
        return 1
    fi

    # 移除旧的代理设置
    npm config delete proxy >/dev/null 2>&1 || true
    npm config delete https-proxy >/dev/null 2>&1 || true

    # 移除 scope 专用源
    npm config delete @anthropic-ai:registry >/dev/null 2>&1 || true
    npm config delete @openai:registry >/dev/null 2>&1 || true
    npm config delete @google:registry >/dev/null 2>&1 || true

    # 设置淘宝镜像
    npm config set registry https://registry.npmmirror.com

    local current_registry
    current_registry=$(npm config get registry)
    info "当前 npm 源: ${current_registry}"

    success "npm 镜像配置完成"
}

# ------------------------------------------------------------------------------
# 阶段 5: CLI 工具安装
# ------------------------------------------------------------------------------

install_claude_code() {
    info "=== [5/9] 安装 Claude Code ==="

    if command_exists claude; then
        warning "检测到 Claude Code 已安装"
        if ask_confirmation "是否更新到最新版本？" "n"; then
            npm install -g @anthropic-ai/claude-code@latest --registry=https://registry.npmmirror.com
            success "Claude Code 更新完成"
        else
            info "跳过 Claude Code 更新"
        fi
    else
        if ask_confirmation "是否安装 Claude Code？（推荐）" "y"; then
            info "正在安装 Claude Code..."
            npm install -g @anthropic-ai/claude-code@latest --registry=https://registry.npmmirror.com
            success "Claude Code 安装完成"
        else
            info "跳过 Claude Code 安装"
        fi
    fi
}

install_codex_cli() {
    info "=== [6/9] 安装 Codex CLI ==="

    if command_exists codex; then
        warning "检测到 Codex CLI 已安装"
        if ask_confirmation "是否更新到最新版本？" "n"; then
            npm install -g @openai/codex --registry=https://registry.npmmirror.com
            success "Codex CLI 更新完成"
        else
            info "跳过 Codex CLI 更新"
        fi
    else
        if ask_confirmation "是否安装 Codex CLI？（推荐）" "y"; then
            info "正在安装 Codex CLI..."
            npm install -g @openai/codex --registry=https://registry.npmmirror.com
            success "Codex CLI 安装完成"
        else
            info "跳过 Codex CLI 安装"
        fi
    fi
}

install_gemini_cli() {
    info "=== [7/9] 安装 Gemini CLI ==="

    if command_exists gemini; then
        warning "检测到 Gemini CLI 已安装"
        if ask_confirmation "是否更新到最新版本？" "n"; then
            npm install -g @google/gemini-cli@latest --registry=https://registry.npmmirror.com
            success "Gemini CLI 更新完成"
        else
            info "跳过 Gemini CLI 更新"
        fi
    else
        if ask_confirmation "是否安装 Gemini CLI？（推荐）" "y"; then
            info "正在安装 Gemini CLI..."
            npm install -g @google/gemini-cli@latest --registry=https://registry.npmmirror.com
            success "Gemini CLI 安装完成"
        else
            info "跳过 Gemini CLI 安装"
        fi
    fi
}

install_droid_cli() {
    info "=== [8/9] 安装 Droid CLI ==="

    if command_exists droid; then
        warning "检测到 Droid CLI 已安装"
        if ask_confirmation "是否重新安装/更新？" "n"; then
            info "通过官方脚本安装 Droid CLI..."
            bash <(curl -fsSL https://app.factory.ai/cli/install.sh)
            success "Droid CLI 安装完成"
        else
            info "跳过 Droid CLI 安装"
        fi
    else
        if ask_confirmation "是否安装 Droid CLI？" "n"; then
            info "通过官方脚本安装 Droid CLI..."
            bash <(curl -fsSL https://app.factory.ai/cli/install.sh)
            success "Droid CLI 安装完成"
        else
            info "跳过 Droid CLI 安装"
        fi
    fi
}

install_openclaw() {
    info "=== 安装 OpenClaw CLI ==="

    if command_exists openclaw; then
        warning "检测到 OpenClaw 已安装"
        if ! ask_confirmation "是否更新到最新版本？" "y"; then
            info "跳过 OpenClaw 更新"
            return 0
        fi
        npm install -g openclaw@latest --registry=https://registry.npmmirror.com
        success "OpenClaw 更新完成"
    else
        if ask_confirmation "是否安装 OpenClaw？（推荐）" "y"; then
            info "正在安装 OpenClaw..."
            npm install -g openclaw@latest --registry=https://registry.npmmirror.com
            success "OpenClaw 安装完成"
        else
            info "跳过 OpenClaw 安装"
        fi
    fi
}

# ------------------------------------------------------------------------------
# 阶段 6: Git 安装
# ------------------------------------------------------------------------------

check_git() {
    if command_exists git; then
        local git_version
        git_version=$(git --version 2>/dev/null || echo "unknown")
        success "检测到 Git 已安装: ${git_version}"
        return 0
    else
        return 1
    fi
}

install_git() {
    info "=== [9/9] 安装 Git ==="

    if check_git; then
        return 0
    fi

    info "未检测到 Git，准备安装..."

    # 优先尝试 Xcode Command Line Tools
    if ask_confirmation "是否通过 Xcode Command Line Tools 安装 Git？（推荐）" "y"; then
        info "正在触发 Xcode Command Line Tools 安装窗口..."
        xcode-select --install 2>/dev/null || true

        warning "请在弹出的窗口中点击'安装'按钮"
        warning "安装完成后，请关闭此脚本并重新运行"
        read -p "按任意键继续..." -n 1 -r
        echo

        if check_git; then
            success "Git 安装成功"
        else
            warning "未检测到 Git，可能安装尚未完成"
        fi
    elif command_exists brew; then
        info "通过 Homebrew 安装 Git..."
        brew install git

        if check_git; then
            success "Git 安装成功"
        else
            error "Git 安装失败"
        fi
    else
        error "无法自动安装 Git，请手动安装："
        error "1. 运行: xcode-select --install"
        error "2. 或访问: https://git-scm.com/download/mac"
    fi
}

# ------------------------------------------------------------------------------
# 阶段 7: Token 配置
# ------------------------------------------------------------------------------

configure_tokens() {
    info "=== [10/9] 配置 API Token ==="

    # 读取 API Base
    local api_base
    read -p "请输入 API Base URL (留空使用默认 ${API_BASE}): " api_base
    api_base="${api_base:-$API_BASE}"

    # 读取 API Key
    local api_key
    read -p "请输入 ShareAI API Token (例如 sk-xxxx，留空则跳过配置): " api_key

    if [ -z "$api_key" ]; then
        warning "未输入 Token，跳过配置"
        return 0
    fi

    # 写入环境变量到 shell 配置文件
    write_env_variables "$api_base" "$api_key"

    # 写入各 CLI 工具的配置文件
    write_claude_config "$api_base" "$api_key"
    write_codex_config "$api_base" "$api_key"
    write_gemini_config "$api_base" "$api_key"

    # 写入 OpenClaw 配置
    write_openclaw_config "$api_base" "$api_key"

    success "Token 配置完成"
    warning "注意: 环境变量需要重新打开终端或执行以下命令后生效:"
    local shell_config
    shell_config=$(get_shell_config)
    info "  source ${shell_config}"
}

write_env_variables() {
    local api_base="$1"
    local api_key="$2"
    local shell_config
    shell_config=$(get_shell_config)

    info "正在将环境变量写入 ${shell_config}..."

    # 备份原配置文件
    cp "${shell_config}" "${shell_config}.backup_$(date +%Y%m%d_%H%M%S)" 2>/dev/null || true

    # 移除旧的配置（如果存在）
    sed -i.bak '/# WQuant AI CLI Environment Variables/,/# End WQuant AI CLI/d' "${shell_config}" 2>/dev/null || true

    # 添加新配置
    cat >> "${shell_config}" << EOF

# WQuant AI CLI Environment Variables
export ANTHROPIC_BASE_URL="${api_base}"
export ANTHROPIC_AUTH_TOKEN="${api_key}"
export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1"
export OPENAI_BASE_URL="${api_base}"
export OPENAI_API_KEY="${api_key}"
export CODE_ASSIST_ENDPOINT="${api_base}"
export GEMINI_API_KEY="${api_key}"
export GOOGLE_GEMINI_BASE_URL="${api_base}"
export GOOGLE_GENAI_USE_GCA="true"
# End WQuant AI CLI

EOF

    success "环境变量已写入 ${shell_config}"
}

write_claude_config() {
    local api_base="$1"
    local api_key="$2"
    local claude_dir="$HOME/.claude"
    local claude_settings="${claude_dir}/settings.json"

    mkdir -p "${claude_dir}"

    if [ -f "${claude_settings}" ] && [ -s "${claude_settings}" ]; then
        if grep -q "ANTHROPIC_BASE_URL" "${claude_settings}"; then
            warning "检测到已有 Claude Code 配置文件"
        else
            warning "检测到已有 Claude Code 配置文件，但未包含 ANTHROPIC_BASE_URL"
        fi

        if ! ask_confirmation "是否覆盖现有配置？" "n"; then
            info "保留原有 Claude Code 配置"
            return 0
        fi
    fi

    cat > "${claude_settings}" << EOF
{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "${api_key}",
    "ANTHROPIC_BASE_URL": "${api_base}",
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"
  },
  "statusLine": {
    "type": "command",
    "command": "npx -y ccstatusline@latest",
    "padding": 0
  },
  "permissions": {
    "allow": [],
    "deny": []
  }
}
EOF

    success "已写入 Claude Code 配置: ${claude_settings}"
}

write_codex_config() {
    local api_base="$1"
    local api_key="$2"
    local codex_dir="$HOME/.codex"
    local codex_config="${codex_dir}/config.toml"
    local codex_auth="${codex_dir}/auth.json"

    mkdir -p "${codex_dir}"

    if [ -f "${codex_config}" ] && [ -s "${codex_config}" ]; then
        if grep -q "base_url" "${codex_config}"; then
            warning "检测到已有 Codex CLI 配置文件"
        else
            warning "检测到已有 Codex CLI 配置文件，但未包含 base_url"
        fi

        if ! ask_confirmation "是否覆盖现有配置？" "n"; then
            info "保留原有 Codex CLI 配置"
            return 0
        fi
    fi

    cat > "${codex_config}" << EOF
disable_response_storage = true
model = "gpt-5.2"
model_reasoning_effort = "high"
model_provider = "share-ai"
sandbox_mode = "danger-full-access"
windows_wsl_setup_acknowledged = true
base_instructions = "Always prefer built-in tools (read_file, list_dir, grep_files) over shell commands for file operations."

[experimental]
use_freeform_apply_patch = true
use_unified_exec_tool = true

[features]
apply_patch_freeform = true
ghost_commit = true
plan_tool = true
rmcp_client = true
streamable_shell = false
unified_exec = false
view_image_tool = true
web_search_request = true
enable_experimental_windows_sandbox = false
experimental_sandbox_command_assessment = true
parallel = true

[model_providers.share-ai]
base_url = "${api_base}/v1"
name = "share-ai"
requires_openai_auth = true
wire_api = "responses"

[sandbox_workspace_write]
network_access = true
EOF

    cat > "${codex_auth}" << EOF
{
  "OPENAI_API_KEY": "${api_key}"
}
EOF

    success "已写入 Codex CLI 配置: ${codex_config}"
    success "已写入 Codex CLI 认证: ${codex_auth}"
}

write_gemini_config() {
    local api_base="$1"
    local api_key="$2"
    local gemini_dir="$HOME/.gemini"
    local gemini_env="${gemini_dir}/.env"
    local gemini_settings="${gemini_dir}/settings.json"
    local gemini_install_id="${gemini_dir}/installation_id"

    mkdir -p "${gemini_dir}"

    if [ -f "${gemini_env}" ] && [ -s "${gemini_env}" ]; then
        if grep -q "GEMINI_API_BASE_URL" "${gemini_env}"; then
            warning "检测到已有 Gemini CLI 配置文件"
        else
            warning "检测到已有 Gemini CLI 配置文件，但未包含 GEMINI_API_BASE_URL"
        fi

        if ! ask_confirmation "是否覆盖现有配置？" "n"; then
            info "保留原有 Gemini CLI 配置"
            return 0
        fi
    fi

    cat > "${gemini_env}" << EOF
GEMINI_API_KEY=${api_key}
GOOGLE_GEMINI_BASE_URL=${api_base}
EOF

    cat > "${gemini_settings}" << EOF
{
  "security": {
    "auth": {
      "selectedType": "gemini-api-key"
    },
    "folderTrust": {
      "enabled": true
    }
  }
}
EOF

    # 生成 installation_id (如果不存在)
    if [ ! -f "${gemini_install_id}" ]; then
        if command_exists uuidgen; then
            uuidgen | tr '[:upper:]' '[:lower:]' > "${gemini_install_id}"
            success "已生成 Gemini CLI 安装 ID"
        else
            warning "无法生成 installation_id (缺少 uuidgen 命令)"
        fi
    else
        info "检测到已有 Gemini CLI 安装 ID"
    fi

    success "已写入 Gemini CLI 配置: ${gemini_env}"
    success "已写入 Gemini CLI 设置: ${gemini_settings}"
}

write_openclaw_config() {
    local api_base="$1"
    local api_key="$2"
    local openclaw_dir="$HOME/.openclaw"
    local openclaw_config="${openclaw_dir}/openclaw.json"

    if ! command_exists openclaw; then
        info "未检测到 OpenClaw CLI，跳过 OpenClaw 配置文件写入"
        return 0
    fi

    mkdir -p "${openclaw_dir}"

    if [ -f "${openclaw_config}" ] && [ -s "${openclaw_config}" ]; then
        if grep -q "shareai" "${openclaw_config}"; then
            warning "检测到已有 OpenClaw 配置文件且已包含 shareai 配置"
        else
            warning "检测到已有 OpenClaw 配置文件"
        fi

        if ! ask_confirmation "是否覆盖现有配置？" "n"; then
            info "保留原有 OpenClaw 配置"
            return 0
        fi
    fi

    # 生成时间戳和随机 Token
    local now_ts
    now_ts=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")
    local gw_token
    if command_exists openssl; then
        gw_token=$(openssl rand -hex 24)
    elif command_exists uuidgen; then
        gw_token=$(uuidgen | tr -d '-' | tr '[:upper:]' '[:lower:]')$(uuidgen | tr -d '-' | tr '[:upper:]' '[:lower:]' | head -c 16)
    else
        gw_token="$(date +%s)$(hostname)$$"
    fi
    local home_dir="$HOME"

    cat > "${openclaw_config}" << EOF
{
  "meta": {
    "lastTouchedVersion": "2026.2.25",
    "lastTouchedAt": "${now_ts}"
  },
  "wizard": {
    "lastRunAt": "${now_ts}",
    "lastRunVersion": "2026.2.6-3",
    "lastRunCommand": "onboard",
    "lastRunMode": "local"
  },
  "models": {
    "mode": "merge",
    "providers": {
      "shareai-openai": {
        "baseUrl": "${api_base}/v1",
        "apiKey": "${api_key}",
        "api": "openai-responses",
        "models": [
          {
            "id": "gpt-5.2",
            "name": "gpt-5.2",
            "reasoning": true
          },
          {
            "id": "gpt-5.3-codex",
            "name": "gpt-5.3-codex",
            "reasoning": true
          },
          {
            "id": "gpt-5.4",
            "name": "gpt-5.4",
            "reasoning": true,
            "input": ["text"],
            "cost": {
              "input": 0,
              "output": 0,
              "cacheRead": 0,
              "cacheWrite": 0
            },
            "contextWindow": 1000000,
            "maxTokens": 8192
          }
        ]
      },
      "shareai-claude": {
        "baseUrl": "${api_base}/",
        "apiKey": "${api_key}",
        "api": "anthropic-messages",
        "models": [
          {
            "id": "claude-opus-4-6",
            "name": "claude-opus-4-6",
            "reasoning": true,
            "maxTokens": 8192
          }
        ]
      }
    }
  },
  "agents": {
    "defaults": {
      "model": {
        "primary": "shareai-openai/gpt-5.4"
      },
      "workspace": "${home_dir}/.openclaw/workspace",
      "compaction": {
        "reserveTokensFloor": 300000,
        "memoryFlush": {
          "enabled": true,
          "softThresholdTokens": 20000
        }
      },
      "timeoutSeconds": 1800,
      "maxConcurrent": 10,
      "subagents": {
        "maxConcurrent": 20,
        "maxSpawnDepth": 2,
        "maxChildrenPerAgent": 5,
        "runTimeoutSeconds": 900
      }
    }
  },
  "tools": {
    "profile": "full"
  },
  "messages": {
    "ackReactionScope": "group-mentions"
  },
  "commands": {
    "native": "auto",
    "nativeSkills": "auto",
    "restart": true,
    "ownerDisplay": "raw"
  },
  "skills": {
    "install": {
      "nodeManager": "npm"
    }
  },
  "gateway": {
    "port": 18789,
    "mode": "local",
    "bind": "loopback",
    "auth": {
      "mode": "token",
      "token": "${gw_token}"
    }
  }
}
EOF

    success "已写入 OpenClaw 配置: ${openclaw_config}"
}

# ------------------------------------------------------------------------------
# 阶段 8: Terminal 推荐
# ------------------------------------------------------------------------------

recommend_iterm2() {
    info "=== [11/9] 终端推荐 ==="

    info "macOS 自带 Terminal.app 已足够使用"
    info "如需更强大的终端功能，推荐安装 iTerm2"

    if ask_confirmation "是否了解 iTerm2 安装方式？" "n"; then
        info "iTerm2 安装方式："
        info "1. 通过 Homebrew: brew install --cask iterm2"
        info "2. 官方下载: https://iterm2.com/downloads.html"

        if command_exists brew; then
            if ask_confirmation "是否现在通过 Homebrew 安装 iTerm2？" "n"; then
                brew install --cask iterm2
                success "iTerm2 安装完成"
            fi
        fi
    fi
}

# ------------------------------------------------------------------------------
# 主流程
# ------------------------------------------------------------------------------

main() {
    echo "=============================================="
    echo "  WQuant AI CLI 工具一键安装脚本 (macOS)"
    echo "=============================================="
    echo ""

    # 阶段 1: 前置检查
    check_prerequisites
    check_sudo_permission

    # 阶段 2: Homebrew
    install_homebrew

    # 阶段 3: Node.js
    install_node_from_mirror

    # 阶段 4: npm 镜像
    configure_npm_mirror

    # 阶段 5: CLI 工具
    install_claude_code
    install_codex_cli
    install_gemini_cli
    install_droid_cli

    install_openclaw

    # 阶段 6: Git
    install_git

    # 阶段 7: Token 配置
    configure_tokens

    # 阶段 8: Terminal 推荐
    recommend_iterm2

    # 完成提示
    echo ""
    echo "=============================================="
    success "所有任务执行完毕！"
    echo "=============================================="
    echo ""
    info "重要提示："
    info "1. 环境变量需要重新打开终端或执行以下命令后生效:"
    local shell_config
    shell_config=$(get_shell_config)
    info "   source ${shell_config}"
    echo ""
    info "2. 如命令 (claude / codex / gemini / droid / openclaw) 无法识别，请:"
    info "   - 关闭当前终端窗口"
    info "   - 重新打开终端"
    info "   - 测试命令: claude --version"
    echo ""
    info "3. 使用 CLI 时如需代理，请配置系统代理或环境变量:"
    info "   export HTTP_PROXY=http://127.0.0.1:7890"
    info "   export HTTPS_PROXY=http://127.0.0.1:7890"
    echo ""
    info "4. 各 CLI 工具的使用方法请参考官方文档"
    echo ""
    warning "如遇到问题，请查看以下日志文件或联系技术支持"
    echo "=============================================="
    echo ""
}

# 执行主流程
main "$@"
