#!/bin/bash

# Claude Code 配置工具 - Linux/macOS 版本
# 使用方法: bash <(curl -fsSL https://your-url/setup_claude.sh)

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

# 输出函数
print_success() { echo -e "${GREEN}[✓]${NC} $1"; }
print_error() { echo -e "${RED}[✗]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[!]${NC} $1"; }
print_info() { echo -e "${CYAN}[ℹ]${NC} $1"; }

# 打印标题
print_header() {
    echo ""
    echo -e "${CYAN}========================================${NC}"
    echo -e "${CYAN}      Claude Code 配置工具${NC}"
    echo -e "${CYAN}========================================${NC}"
    echo ""
}

# 检测操作系统
detect_os() {
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="Linux"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macOS"
    else
        OS="Unknown"
    fi
    print_info "检测到操作系统: $OS"
}

# 主安装函数
install_claude_config() {
    print_header
    detect_os
    
    # 设置路径
    CLAUDE_PATH="$HOME/.claude"
    SETTINGS_PATH="$CLAUDE_PATH/settings.json"
    
    # 创建目录
    if [ -d "$CLAUDE_PATH" ]; then
        print_info "目录已存在: $CLAUDE_PATH"
    else
        mkdir -p "$CLAUDE_PATH"
        print_success "已创建目录: $CLAUDE_PATH"
    fi
    
    # 检查现有配置
    if [ -f "$SETTINGS_PATH" ]; then
        print_warning "配置文件已存在: $SETTINGS_PATH"
        read -p "是否覆盖? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            print_error "已取消安装"
            exit 1
        fi
    fi
    
    # 创建配置文件
    cat > "$SETTINGS_PATH" <<'EOF'
{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "sk-xxx",
    "ANTHROPIC_BASE_URL": "https://api.lingyaai.cn"
  }
}
EOF
    
    print_success "已创建配置文件: $SETTINGS_PATH"
    
    # 设置权限
    chmod 600 "$SETTINGS_PATH"
    print_success "已设置文件权限为 600"
    
    # 完成提示
    echo ""
    echo -e "${CYAN}========================================${NC}"
    print_success "安装完成！"
    echo -e "${CYAN}========================================${NC}"
    echo ""
    print_warning "下一步操作："
    echo "1. 访问 https://api.lingyaai.cn 获取 API 密钥"
    echo "2. 编辑配置文件填入密钥："
    echo -e "   ${YELLOW}nano $SETTINGS_PATH${NC}"
    echo "   或"
    echo -e "   ${YELLOW}vi $SETTINGS_PATH${NC}"
    echo ""
    
    # 询问是否立即编辑
    read -p "是否现在编辑配置文件? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        if command -v nano &> /dev/null; then
            nano "$SETTINGS_PATH"
        elif command -v vi &> /dev/null; then
            vi "$SETTINGS_PATH"
        else
            print_error "未找到文本编辑器，请手动编辑文件"
        fi
    fi
    
    echo ""
    print_info "配置文件位置: $SETTINGS_PATH"
}

# 执行安装
install_claude_config
