#!/usr/bin/env bash
# codebuddy-mem 一键安装脚本
# 用法：bash install.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_DIR="${HOME}/.codebuddy-mem"

echo "=== codebuddy-mem v13.0.0 安装 ==="

# 1. 复制到安装目录
if [ "$SCRIPT_DIR" != "$INSTALL_DIR" ]; then
  echo "复制文件到 ${INSTALL_DIR}..."
  rsync -a --exclude='node_modules' --exclude='.git' "$SCRIPT_DIR/" "$INSTALL_DIR/"
fi

# 2. 检测运行时
RUNTIME=""
if command -v bun &>/dev/null; then
  RUNTIME="bun"
  echo "检测到 Bun: $(bun --version)"
elif command -v node &>/dev/null; then
  RUNTIME="node"
  NODE_VERSION=$(node -v | sed 's/v//')
  echo "检测到 Node.js: v${NODE_VERSION}"
  if [ "$(echo "$NODE_VERSION" | cut -d. -f1)" -lt 18 ]; then
    echo "错误: Node.js >= 18 需要，当前版本 ${NODE_VERSION}"
    exit 1
  fi
else
  echo "错误: 未检测到 Bun 或 Node.js。请先安装。"
  echo "  Bun:  curl -fsSL https://bun.sh/install | bash"
  echo "  Node: https://nodejs.org/"
  exit 1
fi

# 3. 安装依赖
echo "安装依赖..."
cd "$INSTALL_DIR"
if [ "$RUNTIME" = "bun" ]; then
  bun install --production
else
  npm install --production
fi

# 4. 创建配置目录
mkdir -p "${HOME}/.codebuddy-mem"

# 5. 检查 MCP 配置
MCP_FILE="${HOME}/.codebuddy/.mcp.json"
if [ -f "$MCP_FILE" ]; then
  if grep -q '"codebuddy-mem"' "$MCP_FILE" 2>/dev/null; then
    echo "MCP 配置已存在，跳过。"
  else
    echo "请在 ${MCP_FILE} 中添加 codebuddy-mem 配置："
    echo ""
    echo '  "codebuddy-mem": {'
    echo '    "type": "stdio",'
    echo "    \"command\": \"${RUNTIME}\","
    echo "    \"args\": [\"${INSTALL_DIR}/scripts/mcp-server.cjs\"]"
    echo '  }'
  fi
else
  echo "创建默认 MCP 配置..."
  mkdir -p "$(dirname "$MCP_FILE")"
  cat > "$MCP_FILE" <<EOF
{
  "mcpServers": {
    "codebuddy-mem": {
      "type": "stdio",
      "command": "${RUNTIME}",
      "args": ["${INSTALL_DIR}/scripts/mcp-server.cjs"]
    }
  }
}
EOF
fi

# 6. 完成
echo ""
echo "=== 安装完成 ==="
echo "配置文件: ${HOME}/.codebuddy-mem/settings.json"
echo "数据目录: ${HOME}/.codebuddy-mem/"
echo ""
echo "如需配置 DeepSeek API Key："
echo "  echo '{\"CODEBUDDY_MEM_DEEPSEEK_API_KEY\":\"sk-xxx\"}' > ${HOME}/.codebuddy-mem/settings.json"
echo ""
echo "重启 CodeBuddy Code 生效。"
