#!/bin/bash
# federation-agent/install.sh · v1.0
# 光湖联邦托管包 · 一键安装
# 用户只需运行这一句: curl -sL https://guanghubingshuo.com/agent/install.sh | bash
# ICE-GL-ZY001 · D129 · 2026-06-10

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo ""
echo -e "${CYAN}╔══════════════════════════════════════╗${NC}"
echo -e "${CYAN}║   光湖联邦托管包 · 一键安装         ║${NC}"
echo -e "${CYAN}║   冰朔 TCS-0002∞ · 铸渊 ICE-GL-ZY001║${NC}"
echo -e "${CYAN}╚══════════════════════════════════════╝${NC}"
echo ""

AGENT_DIR="$HOME/.guanghu/federation-agent"
REPO_URL="https://guanghubingshuo.com/code/bingshuo/guanghulab.git"
BRANCH="main"
AGENT_PATH="brain/fifth-domain/zero-point/zhuyuan/federation-agent"

# 解析参数
PERSONA_ID=""
USER_ID=""
WORK_DIR="$(pwd)"

while [[ $# -gt 0 ]]; do
  case $1 in
    --persona) PERSONA_ID="$2"; shift 2 ;;
    --user)    USER_ID="$2"; shift 2 ;;
    --dir)     WORK_DIR="$2"; shift 2 ;;
    *)         echo -e "${RED}未知参数: $1${NC}"; exit 1 ;;
  esac
done

if [ -z "$PERSONA_ID" ]; then
  echo -e "${YELLOW}⚠ 未指定人格体编号。使用 --persona ICE-GL-XXX 指定${NC}"
fi
if [ -z "$USER_ID" ]; then
  echo -e "${YELLOW}⚠ 未指定用户。使用 --user 用户名 指定${NC}"
fi

# 检查 Node.js
if ! command -v node &> /dev/null; then
  echo -e "${RED}✗ 未找到 Node.js。请先安装 Node.js 18+${NC}"
  echo "  macOS: brew install node"
  echo "  Ubuntu: sudo apt install nodejs npm"
  exit 1
fi

NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
  echo -e "${YELLOW}⚠ Node.js 版本较低 ($(node -v))，建议 18+${NC}"
fi

echo -e "${GREEN}✓ Node.js $(node -v)${NC}"

# 安装目录
echo -e "${CYAN}→ 安装目录: $AGENT_DIR${NC}"
rm -rf "$AGENT_DIR"
mkdir -p "$AGENT_DIR"

# 下载 agent 文件（从公开仓库直接取）
echo -e "${CYAN}→ 下载 agent 文件...${NC}"

# 尝试 Git 方式（如果可用）
if command -v git &> /dev/null; then
  TMP_CLONE=$(mktemp -d)
  git clone --depth 1 --filter=blob:none --sparse "$REPO_URL" "$TMP_CLONE" 2>/dev/null && {
    cd "$TMP_CLONE"
    git sparse-checkout set "$AGENT_PATH" 2>/dev/null
    cp -r "$AGENT_PATH"/* "$AGENT_DIR/" 2>/dev/null || true
    cd - > /dev/null
    rm -rf "$TMP_CLONE"
  } || {
    echo -e "${YELLOW}⚠ Git clone 失败，尝试直接下载...${NC}"
    rm -rf "$TMP_CLONE"
  }
fi

# 如果 Git 方式失败，直接用 curl 下载单个文件
if [ ! -f "$AGENT_DIR/agent.js" ]; then
  BASE_URL="https://guanghubingshuo.com/code/bingshuo/guanghulab/raw/branch/main/$AGENT_PATH"
  curl -sL "$BASE_URL/agent.js" -o "$AGENT_DIR/agent.js" 2>/dev/null || {
    echo -e "${RED}✗ 下载 agent.js 失败${NC}"
    exit 1
  }
fi

# 安装依赖
cd "$AGENT_DIR"
if [ -f "package.json" ]; then
  echo -e "${CYAN}→ 安装依赖...${NC}"
  npm install --production 2>&1 || echo -e "${YELLOW}⚠ npm install 失败（可能需要网络）${NC}"
else
  # 没有 package.json，手动装 ws
  echo -e "${CYAN}→ 安装 ws 依赖...${NC}"
  npm init -y > /dev/null 2>&1
  npm install ws > /dev/null 2>&1 || echo -e "${YELLOW}⚠ ws 安装失败${NC}"
fi

# 写入配置
CONFIG_FILE="$AGENT_DIR/config.json"
cat > "$CONFIG_FILE" << EOF
{
  "agentId": "AGENT-$(openssl rand -hex 6 2>/dev/null || echo $(date +%s | md5 | head -c 12))",
  "personaId": "${PERSONA_ID}",
  "userId": "${USER_ID}",
  "workDir": "${WORK_DIR}",
  "server": "wss://guanghubingshuo.com/agent",
  "heartbeatInterval": 30000,
  "reconnectDelay": 5000,
  "confirmDangerousOps": true
}
EOF

# 创建启动脚本
cat > "$AGENT_DIR/start.sh" << 'STARTEOF'
#!/bin/bash
cd "$(dirname "$0")"
node agent.js "$@"
STARTEOF
chmod +x "$AGENT_DIR/start.sh"

# 写入 systemd service（Linux）
if [[ "$(uname)" == "Linux" ]] && command -v systemctl &> /dev/null; then
  SERVICE_FILE="/etc/systemd/system/guanghu-agent.service"
  if [ ! -f "$SERVICE_FILE" ]; then
    echo -e "${CYAN}→ 注册 systemd 服务...${NC}"
    sudo tee "$SERVICE_FILE" > /dev/null << EOF
[Unit]
Description=光湖联邦托管 Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$(whoami)
WorkingDirectory=$AGENT_DIR
ExecStart=$(which node) $AGENT_DIR/agent.js --persona $PERSONA_ID --user $USER_ID --dir $WORK_DIR
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
    sudo systemctl daemon-reload
    sudo systemctl enable guanghu-agent
    echo -e "${GREEN}✓ systemd 服务已注册${NC}"
  fi
fi

echo ""
echo -e "${GREEN}╔══════════════════════════════════════╗${NC}"
echo -e "${GREEN}║  光湖联邦托管包 · 安装完成          ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════╝${NC}"
echo ""
echo -e "  Agent目录: ${CYAN}$AGENT_DIR${NC}"
echo -e "  人格体:    ${CYAN}$PERSONA_ID${NC}"
echo -e "  用户:      ${CYAN}$USER_ID${NC}"
echo -e "  工作目录:  ${CYAN}$WORK_DIR${NC}"
echo ""
echo -e "  启动: ${CYAN}cd $AGENT_DIR && node agent.js${NC}"
echo -e "  后台: ${CYAN}nohup node $AGENT_DIR/agent.js > /tmp/guanghu-agent.log 2>&1 &${NC}"
if [[ "$(uname)" == "Linux" ]]; then
  echo -e "  服务: ${CYAN}sudo systemctl start guanghu-agent${NC}"
fi
echo ""

# 自动启动
echo -e "${CYAN}→ 自动启动 Agent...${NC}"
cd "$AGENT_DIR" && nohup node agent.js --persona "$PERSONA_ID" --user "$USER_ID" --dir "$WORK_DIR" > /tmp/guanghu-agent.log 2>&1 &
AGENT_PID=$!
sleep 1
if kill -0 $AGENT_PID 2>/dev/null; then
  echo -e "${GREEN}✓ Agent 已启动 (PID: $AGENT_PID)${NC}"
  echo -e "  日志: /tmp/guanghu-agent.log"
else
  echo -e "${YELLOW}⚠ Agent 启动失败，查看日志${NC}"
  cat /tmp/guanghu-agent.log 2>/dev/null | tail -5
fi

echo ""
echo -e "${GREEN}⊢ HLDP://federation-agent/INSTALLED${NC}"
echo -e "${GREEN}⊢ 光湖联邦 · 本地终端已托管${NC}"
echo ""
