#!/bin/bash

set -e

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

# 打印带颜色的消息
info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

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

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

error() {
    echo -e "${RED}❌ $1${NC}"
}

# 标题
echo ""
echo -e "${GREEN}🦞 OpenClaw Relay Channel 安装程序${NC}"
echo ""

# 1. 检查 Node.js
info "检查 Node.js..."
if ! command -v node &> /dev/null; then
    error "需要安装 Node.js"
    echo ""
    echo "请访问：https://nodejs.org/"
    echo "或执行："
    echo "  curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -"
    echo "  sudo apt-get install -y nodejs"
    exit 1
fi

NODE_VERSION=$(node --version)
success "Node.js $NODE_VERSION 已安装"

# 2. 检查 npm
info "检查 npm..."
if ! command -v npm &> /dev/null; then
    error "需要安装 npm"
    echo ""
    echo "请执行："
    echo "  sudo apt-get install -y npm"
    exit 1
fi

NPM_VERSION=$(npm --version)
success "npm $NPM_VERSION 已安装"

# 3. 检查 OpenClaw
info "检查 OpenClaw..."
if ! command -v openclaw &> /dev/null; then
    error "需要安装 OpenClaw"
    echo ""
    echo "请执行："
    echo "  npm install -g openclaw"
    exit 1
fi

OPENCLAW_VERSION=$(openclaw --version 2>&1 | head -1)
success "OpenClaw 已安装 ($OPENCLAW_VERSION)"

# 4. 找到插件目录
PLUGIN_DIR="$HOME/.openclaw/plugins/relay-channel"
WORKSPACE_DIR="$HOME/.openclaw/workspace/openclaw-mobile/relay-channel"

info "安装到：$PLUGIN_DIR"

# 5. 选择安装源
echo ""
echo "选择安装源:"
echo "  1) 本地 workspace (开发模式)"
echo "  2) GitHub (生产模式)"
echo ""
read -p "请选择 [1/2] (默认: 1): " INSTALL_CHOICE

if [ "$INSTALL_CHOICE" = "2" ]; then
    # 从 GitHub 安装
    GITHUB_REPO="${GITHUB_REPO:-your-org/relay-channel}"
    info "从 GitHub 克隆：$GITHUB_REPO"
    
    rm -rf "$PLUGIN_DIR"
    git clone "https://github.com/$GITHUB_REPO.git" "$PLUGIN_DIR"
    cd "$PLUGIN_DIR"
else
    # 从本地 workspace 安装
    if [ -d "$WORKSPACE_DIR" ]; then
        success "从本地 workspace 复制"
        rm -rf "$PLUGIN_DIR"
        cp -r "$WORKSPACE_DIR" "$PLUGIN_DIR"
        cd "$PLUGIN_DIR"
    else
        error "本地 workspace 不存在：$WORKSPACE_DIR"
        exit 1
    fi
fi

# 6. 安装依赖
echo ""
info "安装依赖..."
npm install --production --loglevel=error
success "依赖安装完成"

# 7. 编译
echo ""
info "编译 TypeScript..."
npm run build 2>/dev/null || npx tsc index.ts --outDir dist --skipLibCheck --esModuleInterop --target ES2020 --module commonjs
success "编译完成"

# 8. 配置 OpenClaw
echo ""
info "配置 OpenClaw..."

# 检查配置文件
CONFIG_FILE="$HOME/.openclaw/openclaw.json"
if [ ! -f "$CONFIG_FILE" ]; then
    warning "OpenClaw 配置文件不存在，创建默认配置..."
    mkdir -p "$(dirname "$CONFIG_FILE")"
    echo '{}' > "$CONFIG_FILE"
fi

# 添加插件配置（如果还没有）
if ! grep -q "relay-channel" "$CONFIG_FILE" 2>/dev/null; then
    info "添加 relay-channel 到插件配置..."
    
    # 使用 node 来安全地修改 JSON
    node -e "
      const fs = require('fs');
      const config = JSON.parse(fs.readFileSync('$CONFIG_FILE', 'utf8'));
      
      if (!config.plugins) config.plugins = {};
      if (!config.plugins.entries) config.plugins.entries = {};
      
      config.plugins.entries['relay-channel'] = {
        enabled: true,
        config: {
          wsUrl: 'wss://relayserver.samespace.cn/ws'
        }
      };
      
      fs.writeFileSync('$CONFIG_FILE', JSON.stringify(config, null, 2));
    "
    
    success "插件配置已添加"
else
    info "插件配置已存在"
fi

# 9. 重启 OpenClaw
echo ""
info "重启 OpenClaw..."
openclaw gateway restart
success "OpenClaw 已重启"

# 10. 执行 CLI 显示配对二维码
echo ""
info "生成配对二维码..."
echo ""

# 执行 CLI 工具
node "$PLUGIN_DIR/bin/cli.js" pair

# 完成
echo ""
success "安装完成！"
echo ""
echo "下一步:"
echo "  1. 在 OpenClaw 配置文件中修改中继服务器地址"
echo "     文件：$CONFIG_FILE"
echo ""
echo "  2. 重启 OpenClaw (如果修改了配置)"
echo "     openclaw gateway restart"
echo ""
echo "  3. 用手机 App 扫描上方二维码完成配对"
echo ""
echo "常用命令:"
echo "  /relay pair    - 在 webchat 中生成配对二维码"
echo "  /relay status  - 查看配对状态"
echo "  /relay revoke  - 撤销配对"
echo ""
