#!/bin/bash

################################################################################
# OpenClaw 一键安装脚本
# 版本：v2026.3.12
# 系统要求：Linux/macOS, Node.js 18+, pnpm
################################################################################

set -e

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

# 配置
INSTALL_DIR="${HOME}/.openclaw"
NODE_VERSION="18"
DEFAULT_MODEL="dashscope-coding/qwen3.5-plus"

# Logo
print_logo() {
    echo ""
    echo -e "${BLUE}"
    echo "  _   ____  ___   ____  "
    echo " / \\ |  _ \\|_ _| / ___| "
    echo "/ _ \\| |_) || |  \\___ \\ "
    echo "/ ___ \\  __/ | |   ___) |"
    echo "/_/   \\_\\_| |___| |____/ "
    echo ""
    echo -e "${NC}"
    echo "  OpenClaw 一键安装脚本"
    echo "  版本：v2026.3.12"
    echo ""
}

# 打印信息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

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

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

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

# 检查系统
check_system() {
    print_info "正在检查系统环境..."
    
    # 检查操作系统
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="linux"
        print_success "操作系统：Linux ($(uname -r))"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macos"
        print_success "操作系统：macOS ($(sw_vers -productVersion))"
    else
        print_error "不支持的操作系统：$OSTYPE"
        exit 1
    fi
    
    # 检查 Node.js
    if command -v node &> /dev/null; then
        NODE_VER=$(node -v)
        print_success "Node.js: $NODE_VER"
    else
        print_warning "Node.js 未安装，正在安装 Node.js ${NODE_VERSION}..."
        if [[ "$OS" == "linux" ]]; then
            curl -fsSL https://deb.nodesource.com/setup_${NODE_VERSION}.x | sudo -E bash -
            sudo apt-get install -y nodejs
        else
            brew install node@${NODE_VERSION}
        fi
        print_success "Node.js 安装完成"
    fi
    
    # 检查 pnpm
    if command -v pnpm &> /dev/null; then
        PNPM_VER=$(pnpm -v)
        print_success "pnpm: $PNPM_VER"
    else
        print_warning "pnpm 未安装，正在安装..."
        npm install -g pnpm
        print_success "pnpm 安装完成"
    fi
    
    # 检查磁盘空间
    DISK_SPACE=$(df -h "$HOME" | awk 'NR==2 {print $4}')
    print_success "可用磁盘空间：$DISK_SPACE"
}

# 创建安装目录
create_dirs() {
    print_info "创建安装目录..."
    mkdir -p "$INSTALL_DIR"
    mkdir -p "$INSTALL_DIR/workspace"
    mkdir -p "$INSTALL_DIR/agents/main/sessions"
    mkdir -p "$INSTALL_DIR/extensions"
    print_success "目录创建完成：$INSTALL_DIR"
}

# 下载 OpenClaw
download_openclaw() {
    print_info "下载 OpenClaw..."
    
    cd "$INSTALL_DIR"
    
    # 使用 npm 安装
    if command -v pnpm &> /dev/null; then
        pnpm create openclaw@latest . --yes
    else
        npm create openclaw@latest . --yes
    fi
    
    print_success "OpenClaw 下载完成"
}

# 安装依赖
install_deps() {
    print_info "安装依赖..."
    
    cd "$INSTALL_DIR"
    
    if command -v pnpm &> /dev/null; then
        pnpm install
    else
        npm install
    fi
    
    print_success "依赖安装完成"
}

# 配置文件
setup_config() {
    print_info "生成配置文件..."
    
    CONFIG_FILE="$INSTALL_DIR/config.json"
    
    cat > "$CONFIG_FILE" << EOF
{
  "gateway": {
    "port": 15239,
    "host": "0.0.0.0"
  },
  "channel": {
    "webchat": {
      "enabled": true
    }
  },
  "model": {
    "default": "${DEFAULT_MODEL}"
  },
  "workspace": {
    "path": "${INSTALL_DIR}/workspace"
  }
}
EOF
    
    print_success "配置文件已生成：$CONFIG_FILE"
}

# 安装核心技能
install_skills() {
    print_info "安装核心技能..."
    
    SKILLS_DIR="$INSTALL_DIR/workspace/skills"
    mkdir -p "$SKILLS_DIR"
    
    # 复制内置技能（如果有的话）
    if [ -d "/opt/openclaw/skills" ]; then
        cp -r /opt/openclaw/skills/* "$SKILLS_DIR/" 2>/dev/null || true
        print_success "核心技能已安装"
    else
        print_warning "未找到内置技能，可稍后通过 ClawHub 安装"
    fi
}

# 设置权限
setup_permissions() {
    print_info "设置权限..."
    
    chmod +x "$INSTALL_DIR"/**/*.sh 2>/dev/null || true
    chmod 755 "$INSTALL_DIR"
    
    print_success "权限设置完成"
}

# 初始化数据库
init_database() {
    print_info "初始化数据库..."
    
    # 创建记忆数据库
    MEMORY_DIR="$INSTALL_DIR/workspace/memory"
    mkdir -p "$MEMORY_DIR"
    
    # 创建今日记忆文件
    TODAY=$(date +%Y-%m-%d)
    cat > "$MEMORY_DIR/${TODAY}.md" << EOF
# ${TODAY} 工作日志

## 待办事项
- [ ] 

## 已完成
- [x] OpenClaw 安装完成

## 笔记


EOF
    
    print_success "数据库初始化完成"
}

# 创建启动脚本
create_launcher() {
    print_info "创建启动脚本..."
    
    LAUNCHER="$INSTALL_DIR/start.sh"
    
    cat > "$LAUNCHER" << 'EOF'
#!/bin/bash
# OpenClaw 启动脚本

echo "🦎 正在启动 OpenClaw..."

cd ~/.openclaw

# 启动 Gateway
openclaw gateway start

echo ""
echo "✅ OpenClaw 已启动！"
echo ""
echo "📊 控制面板：http://localhost:15239"
echo "📚 文档：https://docs.openclaw.ai"
echo ""
echo "按 Ctrl+C 停止服务"
EOF
    
    chmod +x "$LAUNCHER"
    print_success "启动脚本已创建：$LAUNCHER"
}

# 显示完成信息
show_completion() {
    echo ""
    echo -e "${GREEN}╔════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║                                                        ║${NC}"
    echo -e "${GREEN}║           🎉 OpenClaw 安装成功！                       ║${NC}"
    echo -e "${GREEN}║                                                        ║${NC}"
    echo -e "${GREEN}╚════════════════════════════════════════════════════════╝${NC}"
    echo ""
    echo "📁 安装目录：$INSTALL_DIR"
    echo "🌐 控制面板：http://localhost:15239"
    echo "📚 官方文档：https://docs.openclaw.ai"
    echo "🦎 社区：https://discord.gg/clawd"
    echo ""
    echo "📋 下一步操作："
    echo "  1. 编辑配置文件：~/.openclaw/config.json"
    echo "  2. 填写您的 API 密钥"
    echo "  3. 运行：openclaw gateway start"
    echo "  4. 访问控制面板开始使用"
    echo ""
    echo "🚀 快速启动："
    echo "  cd $INSTALL_DIR && ./start.sh"
    echo ""
}

# 主函数
main() {
    print_logo
    
    echo "欢迎使用 OpenClaw 一键安装脚本！"
    echo ""
    echo "本脚本将帮助您完成以下操作："
    echo "  ✓ 检查系统环境"
    echo "  ✓ 安装 Node.js 和 pnpm（如需要）"
    echo "  ✓ 下载并安装 OpenClaw"
    echo "  ✓ 配置系统和技能"
    echo "  ✓ 创建启动脚本"
    echo ""
    
    read -p "是否继续安装？[y/N] " -n 1 -r
    echo ""
    
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_info "安装已取消"
        exit 0
    fi
    
    echo ""
    echo "开始安装..."
    echo ""
    
    # 执行安装步骤
    check_system
    echo ""
    
    create_dirs
    echo ""
    
    download_openclaw
    echo ""
    
    install_deps
    echo ""
    
    setup_config
    echo ""
    
    install_skills
    echo ""
    
    setup_permissions
    echo ""
    
    init_database
    echo ""
    
    create_launcher
    echo ""
    
    show_completion
}

# 运行主函数
main "$@"
