#!/usr/bin/env bash
# ============================================================
#  Hermes Agent 一键安装脚本（macOS / Linux / WSL）
#  公开源码，欢迎审查 —— 不放心可先复制给 AI 判断
#  默认配置：云间 API 中转站（https://cloudzone-api.cyou/）
#  功能：检测网络 → 安装 Hermes Agent → 引导配置 CZ API Key → 提示启动网关
# ============================================================

set -u

CLOUDZONE_URL="https://cloudzone-api.cyou"
CLOUDZONE_API_BASE="https://cloudzone-api.cyou/v1"
HERMES_INSTALL_URL="https://hermes-agent.nousresearch.com/install.sh"
GHFAST_PREFIX="https://ghfast.top/"

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; CYAN='\033[0;36m'; NC='\033[0m'
info()  { echo -e "${GREEN}[INFO]${NC} $1"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }
step()  { echo -e "${CYAN}[STEP]${NC} $1"; }
fail()  { error "$1"; error "脚本无法继续。请把以上报错复制给 AI 或到 https://github.com/NousResearch/hermes-agent/issues 求助。"; exit 1; }

# ---------- 第 0 步：检测网络环境（国内 / 国外）----------
detect_network() {
  step "检测网络环境（国内 / 国外）..."
  if curl -fsI --max-time 6 "https://hermes-agent.nousresearch.com" >/dev/null 2>&1; then
    info "可直连 hermes-agent.nousresearch.com，判定为海外网络"
    echo "overseas"
  else
    warn "无法直连，判定为国内网络环境，将用 ghfast.top 代理"
    echo "domestic"
  fi
}

# ---------- 第 1 步：安装 Hermes Agent ----------
install_hermes() {
  local net="$1"
  step "安装 Hermes Agent（官方一键脚本）..."
  local url="$HERMES_INSTALL_URL"
  if [ "$net" = "domestic" ]; then
    url="${GHFAST_PREFIX}${HERMES_INSTALL_URL}"
    info "国内网络：走 ghfast.top 代理拉安装脚本"
  fi
  if curl -fsSL "$url" -o /tmp/hermes_install.sh 2>/dev/null && [ -s /tmp/hermes_install.sh ]; then
    info "下载安装脚本完成，执行安装..."
    bash /tmp/hermes_install.sh || fail "Hermes 安装脚本执行失败"
  else
    fail "无法下载 Hermes 安装脚本（$url 不通？）"
  fi
  rm -f /tmp/hermes_install.sh
  # reload PATH
  export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
  if command -v hermes >/dev/null 2>&1; then
    info "Hermes 安装成功：$(hermes --version 2>/dev/null || echo hermes)"
  else
    warn "hermes 命令尚未在当前 PATH。请执行：source ~/.bashrc（或 ~/.zshrc）后重试 hermes 命令"
  fi
}

# ---------- 第 2 步：引导配置 CZ API Key ----------
setup_api_key() {
  echo ""
  echo "----------------------------------------"
  echo "Hermes 需要一个 LLM API Key 才能跑起来。"
  echo "推荐用云间 API 中转站（国内直连、不用翻墙、价格低至官方两折）："
  echo "  · GPT 低至 0.05x、DeepSeek 0.3x、Claude 0.5x 起"
  echo "  · 支持 90+ 模型，香港节点国模延迟低至 30ms"
  echo ""
  echo "是否现在跳转注册并获取 API Key？"
  echo "  Y - 立即跳转至 ${CLOUDZONE_URL}"
  echo "  N - 我已有 Key，自行输入"
  read -r -p "请选择 [Y/N]: " choice

  local API_KEY=""
  if [ "${choice:-N}" = "Y" ] || [ "${choice:-N}" = "y" ]; then
    info "正在打开浏览器..."
    if command -v xdg-open >/dev/null 2>&1; then
      xdg-open "$CLOUDZONE_URL" >/dev/null 2>&1
    elif command -v open >/dev/null 2>&1; then
      open "$CLOUDZONE_URL" >/dev/null 2>&1
    else
      warn "无法自动打开浏览器，请手动访问：$CLOUDZONE_URL"
    fi
    echo "注册后在「我的 API Key」页面复制 Key（以 sk- 开头）。"
    read -r -p "粘贴你的 API Key: " API_KEY
  else
    # 关闭回显，避免 Key 明文留在终端滚动区
    read -r -s -p "请输入你的 API Key (sk-...): " API_KEY
    echo
  fi

  if [ -z "${API_KEY:-}" ]; then
    warn "未输入 API Key，跳过自动配置。稍后可手动执行：hermes setup"
    return 0
  fi

  # Hermes 用交互式 hermes model / hermes setup 配 provider，无法纯命令行写 Key
  # 这里把 Key 存到环境变量并提示用户在 setup 向导里粘贴
  info "你的 Key 已收到。下面运行 Hermes setup 向导，在选 provider 时："
  echo "  · provider 选 OpenAI 兼容（或 Anthropic）"
  echo "  · base_url 填：$CLOUDZONE_API_BASE"
  echo "  · API Key 填：你的 Key"
  echo ""
  export ANTHROPIC_API_KEY="$API_KEY"
  export ANTHROPIC_BASE_URL="$CLOUDZONE_API_BASE"
  export OPENAI_API_KEY="$API_KEY"
  export OPENAI_BASE_URL="$CLOUDZONE_API_BASE"
  info "已临时设好环境变量（仅本会话）。如要永久生效，加到 ~/.bashrc 或 ~/.zshrc。"
}

# ---------- 第 3 步：提示启动网关 ----------
hint_gateway() {
  echo ""
  step "下一步：把 Hermes 接到 Telegram（可选但强烈推荐）"
  echo "  1. 在 Telegram 找 @BotFather，/newbot 创建一个 bot，拿到 token"
  echo "  2. 运行：hermes gateway setup   （交互式填 token、绑你的 Telegram 账号）"
  echo "  3. 运行：hermes gateway start   （启动网关，建议挂 tmux/screen）"
  echo "  之后在 Telegram 给你的 bot 发消息，就是在跟云端 Hermes agent 对话。"
  echo ""
  echo "完整文档：https://hermes-agent.nousresearch.com/docs/user-guide/messaging"
}

# ---------- 主流程 ----------
main() {
  echo "============================================"
  echo "  Hermes Agent 一键部署"
  echo "  macOS / Linux / WSL 版"
  echo "============================================"
  echo ""

  local NET
  NET=$(detect_network)

  install_hermes "$NET"
  setup_api_key
  hint_gateway

  echo ""
  info "全部完成！"
  echo "  · 启动 CLI：hermes"
  echo "  · 选模型：hermes model"
  echo "  · 启动网关：hermes gateway start"
  echo "  · 诊断：hermes doctor"
  echo ""
  echo "详细教程：https://cleanresolver.com/tutorials/hermes-agent-guide/"
  echo "完整脚本源码已在文末公开，也可从 /scripts/install-hermes-agent.sh 下载"
}

main "$@"
