#!/bin/bash

# 脚本出错时立即退出
# 注意：在 if 条件判断中执行的命令不会触发 set -e 退出
set -e

# --- 辅助函数：安全更新环境变量 ---
update_env_var() {
    local key="$1"
    local value="$2"
    local file="$3"
    
    if [ ! -f "$file" ]; then
        touch "$file"
    fi

    # 构造安全的键值对字符串，使用单引号包裹 value 以处理特殊字符
    # 注意：如果 value 本身包含单引号，这里需要简单的转义处理，但 API Key 通常不含单引号
    # 为了最大兼容性，我们假设 API Key 不含单引号，或者用户手动处理
    local new_line="export $key='$value'"

    # 1. 精确查找是否存在有效的 export 行 (忽略注释行，允许前导空格)
    # ^[[:space:]]*export[[:space:]]+KEY=
    if grep -Eq "^[[:space:]]*export[[:space:]]+$key=" "$file" 2>/dev/null; then
        # 存在则替换 (区分 macOS 和 Linux 的 sed 语法)
        # 使用 -E 启用扩展正则，匹配整行进行替换
        if [[ "$OSTYPE" == "darwin"* ]]; then
            sed -i '' -E "s|^[[:space:]]*export[[:space:]]+$key=.*|$new_line|" "$file"
        else
            sed -i -E "s|^[[:space:]]*export[[:space:]]+$key=.*|$new_line|" "$file"
        fi
    else
        # 不存在则追加
        echo "$new_line" >> "$file"
    fi
}

# --- 交互式菜单函数 ---
show_menu() {
    local options_count=${#model_options[@]}
    
    for ((i=0; i<options_count+1; i++)); do echo ""; done
    tput cuu $((options_count + 1))
    tput civis
    trap "tput cnorm; exit" SIGINT

    local key
    while true; do
        tput cuu $((options_count + 1))
        for i in "${!model_options[@]}"; do
            tput el
            if [ "$i" -eq "$current_selection" ]; then
                echo "  > ${model_options[i]}"
            else
                echo "    ${model_options[i]}"
            fi
        done
        tput el
        echo "Use ↑/↓ to navigate, Enter to select｜使用 ↑/↓ 方向键选择，回车键确认"

        read -s -r -n 1 key
        if [[ $key == $'\x1b' ]]; then
            read -s -r -n 2 rest
            key+="$rest"
        fi

        case "$key" in
            $'\x1b[A') current_selection=$(( (current_selection - 1 + options_count) % options_count )) ;;
            $'\x1b[B') current_selection=$(( (current_selection + 1) % options_count )) ;;
            "") 
                tput cuu $((options_count + 1))
                for ((i=0; i<options_count+1; i++)); do tput el; tput cud 1; done
                tput cuu $((options_count + 1))
                tput cnorm
                break
                ;;
        esac
    done
}

# --- Node.js 环境检查 ---
ensure_nodejs() {
    echo "🔍 Checking Node.js environment...｜检查 Node.js 环境..."
    local need_install=false
    
    if command -v node >/dev/null 2>&1; then
        local current_version=$(node -v | sed 's/v//')
        local major_version=$(echo "$current_version" | cut -d. -f1)
        if [ "$major_version" -ge 18 ]; then
            echo "✅ Node.js is ready: v$current_version"
            return 0
        else
            echo "⚠️  Node.js v$current_version is too old (< 18). Upgrading..."
            need_install=true
        fi
    else
        echo "⚠️  Node.js not found. Installing..."
        need_install=true
    fi

    if [ "$need_install" = true ]; then
        local platform=$(uname -s)
        if [[ "$platform" == "Darwin" ]] && command -v brew >/dev/null 2>&1; then
            echo "🍺 Detected Homebrew. Using brew to install Node.js..."
            brew install node || brew upgrade node
        else
            echo "📥 Installing via NVM..."
            export NVM_DIR="$HOME/.nvm"
            [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

            if ! command -v nvm >/dev/null 2>&1; then
                curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
                [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
            fi
            nvm install 22
            nvm use 22
            nvm alias default 22
        fi
        
        if ! command -v node >/dev/null 2>&1; then
            echo "❌ Node.js installation failed. Please install Node.js v18+ manually."
            exit 1
        fi
    fi
}

ensure_nodejs

# --- Claude Code 安装/更新逻辑 ---
echo "📦 Installing/Updating Claude Code...｜正在安装/更新 Claude Code..."

# 定义安装函数
do_install() {
    npm install -g @anthropic-ai/claude-code
}

# 1. 尝试直接安装
if do_install; then
    echo "✅ Claude Code installed/updated successfully.｜安装成功。"
else
    echo "⚠️  Standard installation failed. Initiating FORCE CLEANUP...｜标准安装失败，开始强制清理..."
    
    GLOBAL_PATH=$(npm root -g 2>/dev/null || echo "/usr/local/lib/node_modules")
    SCOPE_DIR="$GLOBAL_PATH/@anthropic-ai"
    PKG_DIR="$SCOPE_DIR/claude-code"
    
    echo "🧹 Cleaning directory: $PKG_DIR"
    
    # 2. 强制清理 (精确清理 claude-code 和残留的临时目录)
    # 尝试普通删除
    rm -rf "$PKG_DIR" "$SCOPE_DIR"/.claude-code-* 2>/dev/null || true
    
    # 检查是否删除成功 (只要主目录还在，或者有残留临时文件，就视为失败)
    if [ -d "$PKG_DIR" ] || ls "$SCOPE_DIR"/.claude-code-* >/dev/null 2>&1; then
        echo "🔒 Permission denied. Trying cleanup with sudo..."
        if sudo rm -rf "$PKG_DIR" "$SCOPE_DIR"/.claude-code-*; then
            echo "✅ Cleanup successful with sudo."
        else
            echo "❌ Failed to clean up. Please manually run: sudo rm -rf $PKG_DIR"
            exit 1
        fi
    else
        echo "✅ Cleanup successful."
    fi

    # 3. 清理后重试安装
    echo "🔄 Retrying installation...｜重试安装..."
    if do_install; then
        echo "✅ Claude Code installed successfully after cleanup.｜清理后安装成功。"
    else
        echo "🔒 Permission denied during install. Trying with sudo...｜安装权限不足，尝试 sudo..."
        if sudo npm install -g @anthropic-ai/claude-code; then
            echo "✅ Claude Code installed successfully with sudo.｜使用 sudo 安装成功。"
        else
            echo "❌ Installation failed. Please check your npm permissions."
            exit 1
        fi
    fi
fi

# --- 配置 Claude Code ---
echo "⚙️  Configuring Claude Code..."
node --eval '
    const fs = require("fs");
    const os = require("os");
    const path = require("path");
    const homeDir = os.homedir(); 
    const filePath = path.join(homeDir, ".claude.json");
    try {
        let config = {};
        if (fs.existsSync(filePath)) {
            config = JSON.parse(fs.readFileSync(filePath, "utf-8"));
        }
        config.hasCompletedOnboarding = true;
        fs.writeFileSync(filePath, JSON.stringify(config, null, 2), "utf-8");
    } catch (e) {}'

# --- 环境变量配置 ---
current_shell=$(basename "$SHELL")
case "$current_shell" in
    bash) rc_file="$HOME/.bashrc" ;;
    zsh) rc_file="$HOME/.zshrc" ;;
    *) rc_file="$HOME/.profile" ;;
esac

api_key=""
# 检查现有 Key
if [ -f "$rc_file" ]; then
    # 使用 grep -E 匹配 export 行，并排除注释行 (简单过滤)
    existing_line=$(grep -E "^[[:space:]]*export[[:space:]]+ANTHROPIC_API_KEY=" "$rc_file" 2>/dev/null | tail -n 1 || true)
    
    if [ -n "$existing_line" ]; then
        if grep -q "siliconflow.cn" "$rc_file" 2>/dev/null; then
            echo ""
            echo "✅ Detected existing configuration. Using saved API Key.｜检测到已有配置，使用已保存的 Key。"
            # 提取 Key 值，处理引号
            api_key=$(echo "$existing_line" | cut -d'=' -f2- | sed -e "s/^'//" -e "s/'$//" -e 's/^"//' -e 's/"$//')
        fi
    fi
fi

if [ -z "$api_key" ]; then
    echo ""
    echo "🔑 Please enter your SiliconCloud API Key｜设置你的 SiliconCloud API Key:"
    echo "   Get it here: https://cloud.siliconflow.cn/account/ak"
    echo "   (Input hidden for security｜输入内容已隐藏)"
    echo ""
    read -s api_key
    echo ""

    if [ -z "$api_key" ]; then
        echo "⚠️  API Key cannot be empty. Exiting."
        exit 1
    fi
fi

# --- 模型选择 ---
echo ""
echo "🤖 Please select a model to use｜请选择需要使用的模型:"

model_options=(
    "Pro/moonshotai/Kimi-K2.5"
    "Pro/MiniMaxAI/MiniMax-M2.1"
    "Pro/zai-org/GLM-4.7"
    "Pro/deepseek-ai/DeepSeek-V3.2"
    "Pro/deepseek-ai/DeepSeek-V3.1-Terminus"
    "Qwen/Qwen3-Coder-480B-A35B-Instruct"
    "Custom (enter your own model)｜自定义 (手动输入模型)"
)
current_selection=0

show_menu

custom_option_index=$((${#model_options[@]} - 1))

if [ "$current_selection" -eq "$custom_option_index" ]; then
    echo ""
    echo "✍️ Please enter the custom model name｜请输入自定义模型名称:"
    read -r custom_model_name
    
    if [ -z "$custom_model_name" ]; then
        echo "⚠️ Model name cannot be empty."
        exit 1
    fi
    selected_model="$custom_model_name"
else
    selected_model=${model_options[$current_selection]}
fi

echo ""
echo "✅ Selected model: $selected_model"

# --- 更新环境变量 ---
echo ""
echo "📝 Updating environment variables in $rc_file...｜正在更新环境变量..."

# 0. 创建备份 (Safety First)
cp "$rc_file" "${rc_file}.bak.$(date +%s)" 2>/dev/null || true

# 1. 处理 Header (防止重复添加)
HEADER="# Claude Code environment variables (Added/Updated by script)"
# 使用 -F 固定字符串匹配，-x 整行匹配 (如果可能)，这里用 grep -Fq 足够
if ! grep -Fq "$HEADER" "$rc_file" 2>/dev/null; then
    # 确保文件末尾有换行
    if [ -s "$rc_file" ] && [ "$(tail -c1 "$rc_file" | wc -l)" -eq 0 ]; then
        echo "" >> "$rc_file"
    fi
    echo "$HEADER" >> "$rc_file"
fi

# 2. 更新变量 (使用修复后的安全函数)
update_env_var "ANTHROPIC_BASE_URL" "https://api.siliconflow.cn/" "$rc_file"
update_env_var "ANTHROPIC_API_KEY" "$api_key" "$rc_file"
update_env_var "ANTHROPIC_MODEL" "$selected_model" "$rc_file"

echo "✅ Environment variables successfully updated."

echo ""
echo "🎉 Configuration completed successfully｜配置已完成 🎉"
echo ""
echo "🔄 Please restart your terminal or run｜重新启动终端并运行:"
echo "   source $rc_file"
echo ""
echo "🚀 Then start using Claude Code with｜使用下面命令启动:"
echo "   claude"