#!/bin/bash
# Gemini CLI 一键安装脚本 (Linux/macOS)
# https://api5.ai

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

# 输出函数
print_color() {
    echo -e "${1}${2}${NC}"
}

# 错误处理
set -e
trap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG
trap 'echo -e "${RED}错误: 命令 \"${last_command}\" 在第 ${LINENO} 行失败${NC}"' ERR

# 显示欢迎信息
clear
print_color "$CYAN" "================================================"
print_color "$CYAN" "         Gemini CLI 一键安装程序"
print_color "$CYAN" "         支持最新 Gemini 模型"
print_color "$CYAN" "================================================"
echo ""

# 输入 API KEY
API_KEY=""
while [ -z "$API_KEY" ]; do
    print_color "$YELLOW" "请输入您的 API KEY："
    read -r API_KEY
    if [ -z "$API_KEY" ]; then
        print_color "$RED" "API KEY 不能为空，请重新输入！"
    fi
done

print_color "$GREEN" "✓ API KEY 已接收"
echo ""

# 检测操作系统
detect_os() {
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="linux"
        # 检测 Linux 发行版
        if [ -f /etc/os-release ]; then
            . /etc/os-release
            DISTRO=$ID
        elif [ -f /etc/debian_version ]; then
            DISTRO="debian"
        elif [ -f /etc/redhat-release ]; then
            DISTRO="rhel"
        else
            DISTRO="unknown"
        fi
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macos"
        DISTRO="macos"
    else
        OS="unknown"
        DISTRO="unknown"
    fi

    print_color "$GREEN" "✓ 检测到操作系统: $OS ($DISTRO)"
}

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

# 检查 Node.js 是否已安装
check_node() {
    if command_exists node; then
        NODE_VERSION=$(node --version 2>/dev/null)
        # 提取主版本号
        NODE_MAJOR=$(echo $NODE_VERSION | cut -d. -f1 | sed 's/v//')
        if [ "$NODE_MAJOR" -ge 18 ]; then
            print_color "$GREEN" "✓ 检测到 Node.js 已安装: $NODE_VERSION"
            return 0
        else
            print_color "$YELLOW" "检测到 Node.js $NODE_VERSION，但需要 v18 或更高版本"
            return 1
        fi
    else
        print_color "$YELLOW" "未检测到 Node.js"
        return 1
    fi
}

# 安装 Node.js - macOS
install_node_macos() {
    print_color "$YELLOW" "正在为 macOS 安装 Node.js..."

    # 检查是否有 Homebrew
    if command_exists brew; then
        print_color "$YELLOW" "使用 Homebrew 安装 Node.js..."
        brew install node
    else
        # 安装 Homebrew
        print_color "$YELLOW" "未检测到 Homebrew，正在安装..."
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

        # 配置 Homebrew 环境变量
        if [[ -d "/opt/homebrew" ]]; then
            echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
            eval "$(/opt/homebrew/bin/brew shellenv)"
        fi

        # 安装 Node.js
        brew install node
    fi

    print_color "$GREEN" "✓ Node.js 安装完成"
}

# 安装 Node.js - Linux
install_node_linux() {
    print_color "$YELLOW" "正在为 Linux 安装 Node.js..."

    case $DISTRO in
        ubuntu|debian)
            print_color "$YELLOW" "使用 APT 安装 Node.js..."
            sudo apt update
            sudo apt install -y curl
            curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
            sudo apt install -y nodejs
            ;;
        fedora|rhel|centos)
            print_color "$YELLOW" "使用 YUM/DNF 安装 Node.js..."
            sudo yum install -y curl
            curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
            sudo yum install -y nodejs
            ;;
        arch)
            print_color "$YELLOW" "使用 Pacman 安装 Node.js..."
            sudo pacman -S nodejs npm
            ;;
        *)
            print_color "$YELLOW" "使用 NodeSource 通用安装方法..."
            curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
            sudo apt-get install -y nodejs || sudo yum install -y nodejs
            ;;
    esac

    print_color "$GREEN" "✓ Node.js 安装完成"
}

# 安装 Gemini CLI
install_gemini() {
    print_color "$YELLOW" "正在安装 Gemini CLI..."

    # 使用 npm 安装
    npm install -g @google/gemini-cli@latest

    if [ $? -eq 0 ]; then
        print_color "$GREEN" "✓ Gemini CLI 安装成功"
        return 0
    else
        print_color "$RED" "✗ Gemini CLI 安装失败"
        return 1
    fi
}

# 配置 Gemini CLI 环境变量
configure_gemini() {
    print_color "$YELLOW" "正在配置 Gemini CLI 环境变量..."

    # 检测 shell 配置文件
    if [ "$OS" == "macos" ]; then
        # macOS 默认使用 zsh
        if [ -f "$HOME/.zshrc" ]; then
            SHELL_CONFIG="$HOME/.zshrc"
        else
            SHELL_CONFIG="$HOME/.bash_profile"
        fi
    else
        # Linux 通常使用 bash
        if [ -f "$HOME/.bashrc" ]; then
            SHELL_CONFIG="$HOME/.bashrc"
        elif [ -f "$HOME/.bash_profile" ]; then
            SHELL_CONFIG="$HOME/.bash_profile"
        else
            SHELL_CONFIG="$HOME/.profile"
        fi
    fi

    print_color "$CYAN" "将环境变量写入到: $SHELL_CONFIG"

    # 备份原配置文件
    cp "$SHELL_CONFIG" "$SHELL_CONFIG.backup.$(date +%Y%m%d%H%M%S)"
    print_color "$GREEN" "✓ 已备份原配置文件"

    # 检查是否已存在 Gemini CLI 配置
    if grep -q "# Gemini CLI Configuration" "$SHELL_CONFIG" 2>/dev/null; then
        print_color "$YELLOW" "检测到已存在的 Gemini CLI 配置，正在更新..."
        # 删除旧配置
        sed -i.bak '/# Gemini CLI Configuration Start/,/# Gemini CLI Configuration End/d' "$SHELL_CONFIG"
    fi

    # 添加新的环境变量配置
    cat >> "$SHELL_CONFIG" << EOF

# Gemini CLI Configuration Start
# 设置 Gemini API 基础URL
export GOOGLE_GEMINI_BASE_URL="https://api5.ai"

# 设置您的 API Key
export GEMINI_API_KEY="$API_KEY"

# 启用 GCA 功能
export GOOGLE_GENAI_USE_GCA="true"
# Gemini CLI Configuration End

EOF

    print_color "$GREEN" "✓ 环境变量已写入配置文件"

    # 创建 .gemini 目录
    GEMINI_DIR="$HOME/.gemini"
    mkdir -p "$GEMINI_DIR"
    print_color "$GREEN" "✓ 创建目录: $GEMINI_DIR"

    # 创建 .env 文件作为备份
    cat > "$GEMINI_DIR/.env" << EOF
GEMINI_API_KEY=$API_KEY
GOOGLE_GEMINI_BASE_URL=https://api5.ai
GOOGLE_GENAI_USE_GCA=true
EOF

    print_color "$GREEN" "✓ 创建备份文件: $GEMINI_DIR/.env"

    # 导出环境变量到当前会话
    export GOOGLE_GEMINI_BASE_URL="https://api5.ai"
    export GEMINI_API_KEY="$API_KEY"
    export GOOGLE_GENAI_USE_GCA="true"

    print_color "$GREEN" "✓ 环境变量配置完成"
}

# 验证安装
verify_installation() {
    print_color "$YELLOW" "正在验证安装..."

    if command_exists gemini; then
        print_color "$GREEN" "✓ Gemini CLI 安装验证成功"

        # 尝试获取版本信息
        VERSION=$(gemini --version 2>&1 || echo "版本信息不可用")
        print_color "$CYAN" "  版本: $VERSION"

        # 显示命令位置
        GEMINI_PATH=$(which gemini 2>/dev/null || echo "路径未找到")
        print_color "$CYAN" "  命令位置: $GEMINI_PATH"

        return 0
    else
        print_color "$YELLOW" "⚠ Gemini CLI 命令未找到"
        print_color "$YELLOW" "  可能需要重新加载 shell 配置或重启终端"
        return 0  # 安装成功，只是需要重启
    fi
}

# 主安装流程
main() {
    print_color "$CYAN" "开始安装流程..."
    echo ""

    # 步骤 1: 检测操作系统
    print_color "$CYAN" "[1/5] 检测操作系统..."
    detect_os
    echo ""

    # 步骤 2: 检查并安装 Node.js
    print_color "$CYAN" "[2/5] 检查 Node.js..."
    if ! check_node; then
        print_color "$YELLOW" "正在安装 Node.js v18+..."

        if [ "$OS" == "macos" ]; then
            install_node_macos
        elif [ "$OS" == "linux" ]; then
            install_node_linux
        else
            print_color "$RED" "不支持的操作系统: $OS"
            exit 1
        fi

        # 重新检查安装
        if ! check_node; then
            print_color "$RED" "Node.js 安装失败，请手动安装后重试"
            exit 1
        fi
    fi
    echo ""

    # 步骤 3: 安装 Gemini CLI
    print_color "$CYAN" "[3/5] 安装 Gemini CLI..."
    if ! install_gemini; then
        print_color "$RED" "Gemini CLI 安装失败"
        exit 1
    fi
    echo ""

    # 步骤 4: 配置 Gemini CLI
    print_color "$CYAN" "[4/5] 配置 Gemini CLI..."
    configure_gemini
    echo ""

    # 步骤 5: 验证安装
    print_color "$CYAN" "[5/5] 验证安装..."
    verify_installation
    echo ""

    # 显示安装成功信息
    print_color "$GREEN" "================================================"
    print_color "$GREEN" "         Gemini CLI 安装成功！"
    print_color "$GREEN" "================================================"
    echo ""
    print_color "$CYAN" "使用方法："
    print_color "$WHITE" "  在终端输入 'gemini' 启动 Gemini CLI"
    echo ""
    print_color "$YELLOW" "环境变量（已永久设置）："
    print_color "$WHITE" "  GEMINI_API_KEY = [您的 API Key]"
    print_color "$WHITE" "  GOOGLE_GEMINI_BASE_URL = https://api5.ai"
    print_color "$WHITE" "  GOOGLE_GENAI_USE_GCA = true"
    echo ""
    print_color "$YELLOW" "配置文件位置："
    print_color "$WHITE" "  环境变量: $SHELL_CONFIG"
    print_color "$WHITE" "  备份文件: $HOME/.gemini/.env"
    echo ""

    # 提示重新加载 shell 配置
    print_color "$YELLOW" "重要提示："
    print_color "$WHITE" "  请运行以下命令使环境变量生效："
    if [ "$OS" == "macos" ]; then
        print_color "$CYAN" "  source ~/.zshrc"
    else
        print_color "$CYAN" "  source ~/.bashrc"
    fi
    print_color "$WHITE" "  或者关闭并重新打开终端"
    echo ""
    print_color "$CYAN" "安装完成！"
}

# 运行主函数
main