#!/bin/bash
#
# Hermes Agent macOS 中国大陆安装脚本
#
# 目标：
# - 所有 GitHub / raw.githubusercontent.com 请求使用可达的第三方代理
# - Python 包使用清华 PyPI
# - npm / Playwright / Electron 使用 npmmirror
# - 调用 Hermes 官方 install.sh，尽量不复制官方安装逻辑
#
# 用法：
#   bash install-hermes-cn-macos.sh
#   bash install-hermes-cn-macos.sh --cli-only
#   bash install-hermes-cn-macos.sh --dry-run
#   bash install-hermes-cn-macos.sh --mirrors-only
#

set -euo pipefail

HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
INSTALL_DIR="$HERMES_HOME/hermes-agent"
PYPI_MIRROR="https://pypi.tuna.tsinghua.edu.cn/simple"
NPM_MIRROR="https://registry.npmmirror.com"
PLAYWRIGHT_MIRROR="https://npmmirror.com/mirrors/playwright"
ELECTRON_MIRROR_URL="https://npmmirror.com/mirrors/electron/"
INSTALL_DESKTOP=true
DRY_RUN=false
MIRRORS_ONLY=false

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

info() { printf "${CYAN}[..]${NC} %s\n" "$*"; }
ok() { printf "${GREEN}[OK]${NC} %s\n" "$*"; }
warn() { printf "${YELLOW}[!]${NC} %s\n" "$*"; }
fail() { printf "${RED}[X]${NC} %s\n" "$*" >&2; exit 1; }

run() {
    if [ "$DRY_RUN" = true ]; then
        printf '[DRY RUN] '
        printf '%q ' "$@"
        printf '\n'
    else
        "$@"
    fi
}

usage() {
    cat <<'EOF'
Hermes Agent macOS 中国大陆安装脚本

选项：
  --cli-only       只安装 Hermes CLI，不构建 Hermes.app
  --mirrors-only   只配置国内镜像，不安装 Hermes
  --dry-run        只展示操作，不实际修改或安装
  --help           显示帮助
EOF
}

while [ "$#" -gt 0 ]; do
    case "$1" in
        --cli-only) INSTALL_DESKTOP=false ;;
        --mirrors-only) MIRRORS_ONLY=true ;;
        --dry-run) DRY_RUN=true ;;
        --help|-h) usage; exit 0 ;;
        *) fail "未知参数：$1" ;;
    esac
    shift
done

printf '\n=== Hermes Agent macOS 中国大陆安装 ===\n\n'

[ "$(uname -s)" = "Darwin" ] || fail "本脚本只支持 macOS。"

ARCH="$(uname -m)"
case "$ARCH" in
    arm64) ok "检测到 Apple Silicon Mac（arm64）" ;;
    x86_64) ok "检测到 Intel Mac（x86_64）" ;;
    *) fail "不支持的 Mac 架构：$ARCH" ;;
esac

command -v curl >/dev/null 2>&1 || fail "系统缺少 curl。"

if ! command -v git >/dev/null 2>&1 || ! git --version >/dev/null 2>&1; then
    warn "未检测到可用 Git，将打开 Apple Command Line Tools 安装窗口。"
    if [ "$DRY_RUN" = false ]; then
        xcode-select --install >/dev/null 2>&1 || true
    fi
    fail "请完成 Apple Command Line Tools 安装，再重新运行本脚本。"
fi
ok "$(git --version)"

probe() {
    curl -fsIL --max-time 12 "$1" >/dev/null 2>&1
}

info "探测可用的 GitHub 第三方代理..."
GITHUB_PROXY=""
for candidate in \
    "https://ghfast.top/" \
    "https://ghproxy.net/" \
    "https://gh-proxy.org/"
do
    test_url="${candidate}https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh"
    if probe "$test_url"; then
        GITHUB_PROXY="$candidate"
        ok "可用 GitHub 代理：$candidate"
        break
    fi
    warn "不可用：$candidate"
done
[ -n "$GITHUB_PROXY" ] || fail "第三方 GitHub 代理全部不可用，请更换网络后重试。"

info "检查国内依赖源..."
probe "$PYPI_MIRROR/" || fail "清华 PyPI 当前不可用：$PYPI_MIRROR"
probe "$NPM_MIRROR/" || fail "npmmirror npm 当前不可用：$NPM_MIRROR"
probe "$ELECTRON_MIRROR_URL" || fail "npmmirror Electron 当前不可用：$ELECTRON_MIRROR_URL"
ok "国内依赖源可访问"

info "配置 GitHub、PyPI、npm、Playwright、Electron 国内源..."

# 持久化 GitHub URL 重写，确保后续 hermes update 也不直连 GitHub。
GIT_REWRITE_KEY="url.${GITHUB_PROXY}https://github.com/.insteadOf"
run git config --global --replace-all "$GIT_REWRITE_KEY" "https://github.com/"

# uv 在官方安装器中设置了 UV_NO_CONFIG=1，因此安装阶段必须依赖环境变量。
export UV_DEFAULT_INDEX="$PYPI_MIRROR"
export PIP_INDEX_URL="$PYPI_MIRROR"
export PLAYWRIGHT_DOWNLOAD_HOST="$PLAYWRIGHT_MIRROR"
export ELECTRON_MIRROR="$ELECTRON_MIRROR_URL"
export npm_config_registry="$NPM_MIRROR"
export npm_config_electron_mirror="$ELECTRON_MIRROR_URL"
export GIT_TERMINAL_PROMPT=0

if [ "$DRY_RUN" = false ]; then
    mkdir -p "$HOME/.config/uv"
    cat > "$HOME/.config/uv/uv.toml" <<EOF
[[index]]
url = "$PYPI_MIRROR"
default = true
EOF
fi

if command -v npm >/dev/null 2>&1; then
    run npm config set registry "$NPM_MIRROR"
fi

SHELL_RC="$HOME/.zshrc"
BEGIN_MARKER="# >>> Hermes China mirrors >>>"
END_MARKER="# <<< Hermes China mirrors <<<"
if [ "$DRY_RUN" = false ]; then
    touch "$SHELL_RC"
    tmp_rc="$(mktemp)"
    awk -v begin="$BEGIN_MARKER" -v end="$END_MARKER" '
        $0 == begin { skip=1; next }
        $0 == end { skip=0; next }
        !skip { print }
    ' "$SHELL_RC" > "$tmp_rc"
    cat >> "$tmp_rc" <<EOF

$BEGIN_MARKER
export UV_DEFAULT_INDEX="$PYPI_MIRROR"
export PIP_INDEX_URL="$PYPI_MIRROR"
export PLAYWRIGHT_DOWNLOAD_HOST="$PLAYWRIGHT_MIRROR"
export ELECTRON_MIRROR="$ELECTRON_MIRROR_URL"
export npm_config_registry="$NPM_MIRROR"
export npm_config_electron_mirror="$ELECTRON_MIRROR_URL"
export PATH="\$HOME/.local/bin:\$HOME/.hermes/bin:\$HOME/.hermes/node/bin:\$PATH"
$END_MARKER
EOF
    mv "$tmp_rc" "$SHELL_RC"
fi
ok "国内源配置完成"

if [ "$MIRRORS_ONLY" = true ]; then
    ok "MirrorsOnly 完成，未安装 Hermes。"
    exit 0
fi

OFFICIAL_INSTALL_URL="${GITHUB_PROXY}https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh"
TMP_INSTALL="$(mktemp /tmp/hermes-install-cn.XXXXXX.sh)"
trap 'rm -f "$TMP_INSTALL"' EXIT

info "通过第三方代理下载 Hermes 官方 macOS 安装器..."
if [ "$DRY_RUN" = false ]; then
    curl -fsSL --max-time 90 "$OFFICIAL_INSTALL_URL" -o "$TMP_INSTALL"
    [ "$(wc -c < "$TMP_INSTALL")" -gt 30000 ] || fail "下载的官方安装器异常或不完整。"

    # 禁止官方安装器尝试 GitHub SSH / 直连 HTTPS。
    # 仓库地址直接替换为当前探测成功的第三方代理地址。
    PROXIED_REPO="${GITHUB_PROXY}https://github.com/NousResearch/hermes-agent.git"
    sed -i '' \
        -e "s|^REPO_URL_SSH=.*|REPO_URL_SSH=\"$PROXIED_REPO\"|" \
        -e "s|^REPO_URL_HTTPS=.*|REPO_URL_HTTPS=\"$PROXIED_REPO\"|" \
        "$TMP_INSTALL"
    chmod +x "$TMP_INSTALL"
else
    info "DryRun：将下载 $OFFICIAL_INSTALL_URL"
fi

INSTALL_ARGS=(--skip-setup --non-interactive)
if [ "$INSTALL_DESKTOP" = true ]; then
    INSTALL_ARGS+=(--include-desktop)
fi

info "运行 Hermes 官方安装器..."
if [ "$DRY_RUN" = true ]; then
    printf '[DRY RUN] bash %q ' "$TMP_INSTALL"
    printf '%q ' "${INSTALL_ARGS[@]}"
    printf '\n'
else
    bash "$TMP_INSTALL" "${INSTALL_ARGS[@]}"
fi

info "写入 Hermes venv 国内源配置..."
VENV_DIR="$INSTALL_DIR/venv"
if [ -d "$VENV_DIR" ] && [ "$DRY_RUN" = false ]; then
    cat > "$VENV_DIR/uv.toml" <<EOF
[[index]]
url = "$PYPI_MIRROR"
default = true
EOF
    cat > "$INSTALL_DIR/uv.toml" <<EOF
[[index]]
url = "$PYPI_MIRROR"
default = true
EOF
    ok "已写入 venv 和项目级 uv.toml"
else
    warn "未找到 ${VENV_DIR}，跳过 venv 国内源配置。"
fi

info "验证 Hermes..."
HERMES_BIN=""
for candidate in \
    "$HOME/.local/bin/hermes" \
    "$VENV_DIR/bin/hermes" \
    "$(command -v hermes 2>/dev/null || true)"
do
    if [ -n "$candidate" ] && [ -x "$candidate" ]; then
        HERMES_BIN="$candidate"
        break
    fi
done

if [ "$DRY_RUN" = true ]; then
    ok "DryRun 完成。"
elif [ -z "$HERMES_BIN" ]; then
    fail "安装结束但未找到 hermes 命令，请检查上方安装日志。"
else
    "$HERMES_BIN" --version
    ok "Hermes CLI 安装成功：$HERMES_BIN"
fi

if [ "$INSTALL_DESKTOP" = true ] && [ "$DRY_RUN" = false ]; then
    APP_PATH=""
    for candidate in \
        "$INSTALL_DIR/apps/desktop/release/mac-arm64/Hermes.app" \
        "$INSTALL_DIR/apps/desktop/release/mac/Hermes.app" \
        "$INSTALL_DIR/apps/desktop/dist/mac-arm64/Hermes.app" \
        "$INSTALL_DIR/apps/desktop/dist/mac/Hermes.app"
    do
        if [ -d "$candidate" ]; then APP_PATH="$candidate"; break; fi
    done
    if [ -n "$APP_PATH" ]; then
        ok "Hermes.app 构建成功：$APP_PATH"
        info "可运行：open \"$APP_PATH\""
    else
        warn "CLI 已安装，但未自动定位到 Hermes.app。可运行：hermes desktop"
    fi
fi

cat <<EOF

=== 安装完成 ===

下一步：
1. 执行：source "$SHELL_RC"
2. 执行：hermes setup
3. 配置可在中国大陆访问的模型 API
4. 执行：hermes --version

GitHub 请求已持续重写到：
$GITHUB_PROXY

如需恢复 GitHub 直连：
git config --global --unset-all "$GIT_REWRITE_KEY"
EOF
