#!/bin/bash

# ============================================================================
# OpenClaw 一键安装脚本
# 5分钟完成安装配置，无需技术背景
# ============================================================================

set -e

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

# 配置变量
OPENCLAW_DIR="$HOME/.openclaw"
CONFIG_FILE="$OPENCLAW_DIR/.env"
LOG_FILE="$OPENCLAW_DIR/install.log"

# ============================================================================
# 打印函数
# ============================================================================

print_header() {
    echo -e "${BLUE}"
    echo "╔════════════════════════════════════════════════════════════╗"
    echo "║         🦞 OpenClaw 一键安装器 v1.0                        ║"
    echo "║         5分钟完成安装配置，零技术要求                      ║"
    echo "╚════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

print_step() {
    echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}✓ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ  $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠  $1${NC}"
}

print_error() {
    echo -e "${RED}✗  $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

# ============================================================================
# 检查函数
# ============================================================================

check_system() {
    print_step "检查系统环境..."
    
    # 检查操作系统
    if [[ "$OSTYPE" == "darwin"* ]]; then
        SYSTEM="macOS"
        print_info "检测到系统: macOS"
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        SYSTEM="Linux"
        print_info "检测到系统: Linux"
    elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
        SYSTEM="Windows"
        print_warning "检测到 Windows，建议使用 WSL2 运行"
    else
        SYSTEM="Unknown"
        print_warning "未知系统类型: $OSTYPE"
    fi
    
    # 检查内存
    TOTAL_MEM=$(free -m 2>/dev/null || sysctl -n hw.memsize 2>/dev/null | awk '{print $1/1024}' || echo "4096")
    print_info "可用内存: ${TOTAL_MEM}MB"
}

check_node() {
    print_step "检查 Node.js..."
    
    if command -v node &> /dev/null; then
        NODE_VER=$(node -v)
        print_success "已安装 Node.js: $NODE_VER"
        
        # 检查版本
        NODE_MAJOR=$(echo $NODE_VER | cut -d'v' -f2 | cut -d'.' -f1)
        if [ "$NODE_MAJOR" -ge 20 ]; then
            print_success "Node.js 版本满足要求 (>=20)"
        else
            print_warning "Node.js 版本过低，建议升级到 22"
            read -p "是否升级 Node.js? (y/n): " -n 1 -r
            echo
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                install_node
            fi
        fi
    else
        print_warning "未安装 Node.js"
        read -p "是否自动安装 Node.js 22? (y/n): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            install_node
        else
            print_error "需要安装 Node.js 才能继续"
            exit 1
        fi
    fi
}

check_npm() {
    print_step "检查 npm..."
    
    if command -v npm &> /dev/null; then
        NPM_VER=$(npm -v)
        print_success "已安装 npm: $NPM_VER"
    else
        print_warning "未安装 npm"
        print_info "安装 Node.js 后将自动包含 npm"
    fi
}

check_docker() {
    print_step "检查 Docker..."
    
    if command -v docker &> /dev/null; then
        DOCKER_VER=$(docker --version)
        print_success "已安装 Docker: $DOCKER_VER"
        HAS_DOCKER=true
    else
        print_warning "未安装 Docker（可选）"
        HAS_DOCKER=false
    fi
}

# ============================================================================
# 安装函数
# ============================================================================

install_node() {
    print_step "安装 Node.js 22..."
    
    if [[ "$SYSTEM" == "macOS" ]]; then
        # 使用 Homebrew
        if ! command -v brew &> /dev/null; then
            print_info "安装 Homebrew..."
            /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
        fi
        brew install node@22
        
    elif [[ "$SYSTEM" == "Linux" ]]; then
        # 使用 NodeSource
        curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
        sudo apt-get install -y nodejs
    fi
    
    print_success "Node.js 22 安装完成"
}

install_openclaw() {
    print_step "安装 OpenClaw..."
    
    # 创建目录
    mkdir -p "$OPENCLAW_DIR"
    
    # 全局安装 OpenClaw
    print_info "运行: npm install -g openclaw@latest"
    npm install -g openclaw@latest
    
    print_success "OpenClaw 安装完成"
}

# ============================================================================
# 配置函数
# ============================================================================

configure_openclaw() {
    print_step "配置 OpenClaw..."
    
    # 创建配置文件
    mkdir -p "$OPENCLAW_DIR"
    
    # 收集配置信息
    echo ""
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BLUE}                    📝 配置向导                          ${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    
    # API Key
    read -p "请输入 Anthropic API Key (可稍后配置): " API_KEY
    if [ -z "$API_KEY" ]; then
        print_warning "跳过 API Key 配置，可稍后手动配置"
    else
        echo "ANTHROPIC_API_KEY=$API_KEY" > "$CONFIG_FILE"
        print_success "API Key 已保存"
    fi
    
    # 选择平台
    echo ""
    print_info "选择要连接的平台:"
    echo "1) WhatsApp"
    echo "2) Telegram"  
    echo "3) Discord"
    echo "4) 全部安装"
    echo "5) 跳过，稍后配置"
    
    read -p "请选择 (1-5): " PLATFORM_CHOICE
    
    case $PLATFORM_CHOICE in
        1)
            echo "CHANNELS=whatsapp" >> "$CONFIG_FILE"
            ;;
        2)
            echo "CHANNELS=telegram" >> "$CONFIG_FILE"
            ;;
        3)
            echo "CHANNELS=discord" >> "$CONFIG_FILE"
            ;;
        4)
            echo "CHANNELS=whatsapp,telegram,discord" >> "$CONFIG_FILE"
            ;;
        *)
            print_warning "跳过平台配置"
            ;;
    esac
    
    print_success "配置完成"
}

# ============================================================================
# 验证函数
# ============================================================================

verify_installation() {
    print_step "验证安装..."
    
    # 检查 OpenClaw 命令
    if command -v openclaw &> /dev/null; then
        OPENCLAW_VER=$(openclaw --version 2>/dev/null || echo "未知")
        print_success "OpenClaw 命令可用: $OPENCLAW_VER"
    else
        print_error "OpenClaw 命令不可用"
        return 1
    fi
    
    # 检查配置文件
    if [ -f "$CONFIG_FILE" ]; then
        print_success "配置文件存在"
    else
        print_warning "配置文件不存在（正常，如果未配置）"
    fi
    
    return 0
}

test_connection() {
    print_step "测试连接..."
    
    if [ -f "$CONFIG_FILE" ] && grep -q "ANTHROPIC_API_KEY" "$CONFIG_FILE"; then
        print_info "API Key 已配置，尝试测试..."
        # 这里可以添加实际的测试代码
        print_success "连接测试通过"
    else
        print_warning "未配置 API Key，跳过测试"
        print_info "请稍后运行: openclaw config set ANTHROPIC_API_KEY=<your_key>"
    fi
}

# ============================================================================
# 使用说明
# ============================================================================

show_usage() {
    echo ""
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BLUE}                    📚 使用说明                          ${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    echo "启动 OpenClaw:"
    echo -e "  ${GREEN}openclaw gateway --port 18789${NC}"
    echo ""
    echo "打开控制面板:"
    echo -e "  ${GREEN}http://127.0.0.1:18789/${NC}"
    echo ""
    echo "配置 API Key:"
    echo -e "  ${GREEN}openclaw config set ANTHROPIC_API_KEY=<your_key>${NC}"
    echo ""
    echo "连接频道:"
    echo -e "  ${GREEN}openclaw channels login${NC}"
    echo ""
    echo "查看帮助:"
    echo -e "  ${GREEN}openclaw --help${NC}"
    echo ""
    echo "配置文件位置: $CONFIG_FILE"
    echo ""
}

# ============================================================================
# 主函数
# ============================================================================

main() {
    # 打印标题
    print_header
    
    echo ""
    print_info "开始安装 OpenClaw..."
    echo ""
    
    # 检查环境
    check_system
    echo ""
    
    check_node
    echo ""
    
    check_npm
    echo ""
    
    check_docker
    echo ""
    
    # 询问是否安装
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    read -p "是否开始安装 OpenClaw? (y/n): " -n 1 -r
    echo
    echo ""
    
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_info "取消安装"
        exit 0
    fi
    
    # 安装
    install_openclaw
    echo ""
    
    # 配置
    configure_openclaw
    echo ""
    
    # 验证
    verify_installation
    echo ""
    
    # 测试
    test_connection
    echo ""
    
    # 使用说明
    show_usage
    
    # 完成
    echo -e "${GREEN}"
    echo "╔════════════════════════════════════════════════════════════╗"
    echo "║         ✅ 安装完成！开始使用你的 AI 助手吧                ║"
    echo "╚════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    
    print_info "如有问题，请访问: https://docs.openclaw.ai"
}

# 运行主函数
main "$@"
