#!/bin/bash
# scripts/vendor_hermes.sh
# 从本地 hermes 仓库打快照到 mindcli/_vendor/
#
# 用法: ./scripts/vendor_hermes.sh [hermes源码路径]
#   或: HERMES_SRC=/path/to/hermes ./scripts/vendor_hermes.sh
#
# 独立仓库，无默认路径——必须显式指定 hermes 源码位置。

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
HERMES_SRC="${1:-${HERMES_SRC:-}}"

if [ -z "$HERMES_SRC" ]; then
    echo "❌ 请指定 hermes 源码路径："
    echo "   $0 /path/to/hermes"
    echo "   或设置环境变量: export HERMES_SRC=/path/to/hermes"
    exit 1
fi
VENDOR_DIR="$PROJECT_DIR/mindcli/_vendor"

# 验证 hermes 源码存在
if [ ! -f "$HERMES_SRC/cli.py" ]; then
    echo "❌ 找不到 hermes 源码: $HERMES_SRC/cli.py"
    echo "用法: $0 [hermes源码路径]"
    exit 1
fi

# 获取 commit hash
COMMIT="unknown"
if cd "$HERMES_SRC" && git rev-parse --short HEAD >/dev/null 2>&1; then
    COMMIT=$(git rev-parse --short HEAD)
fi

echo "📦 Vendoring hermes@$COMMIT → $VENDOR_DIR"

# 清理旧快照
rm -rf "$VENDOR_DIR"
mkdir -p "$VENDOR_DIR"

# 核心模块（单文件）
for pyfile in cli.py run_agent.py mcp_serve.py hermes_state.py hermes_constants.py \
              batch_runner.py model_tools.py utils.py toolsets.py toolset_distributions.py \
              hermes_time.py; do
    if [ -f "$HERMES_SRC/$pyfile" ]; then
        cp "$HERMES_SRC/$pyfile" "$VENDOR_DIR/"
        echo "   ✓ $pyfile"
    else
        echo "   ⚠ $pyfile 不存在，跳过"
    fi
done

# 子模块（目录）
for subdir in hermes_cli tools agent model_tools utils toolsets toolset_distributions gateway cron; do
    if [ -d "$HERMES_SRC/$subdir" ]; then
        cp -r "$HERMES_SRC/$subdir" "$VENDOR_DIR/"
        echo "   ✓ $subdir/"
    else
        echo "   ⚠ $subdir/ 不存在，跳过"
    fi
done

# __init__.py
touch "$VENDOR_DIR/__init__.py"

# 版本锁定标记
cat > "$VENDOR_DIR/VENDOR_COMMIT" << MARKER
# MindOS CLI Vendor Snapshot
source: hermes
commit: $COMMIT
snapshot_date: $(date +%Y-%m-%d)
snapshot_by: vendor_hermes.sh
MARKER

# 统计
FILE_COUNT=$(find "$VENDOR_DIR" -name "*.py" | wc -l | tr -d ' ')
LINE_COUNT=$(find "$VENDOR_DIR" -name "*.py" -exec cat {} + | wc -l | tr -d ' ')

echo "✅ Vendor 完成"
echo "   Commit:  $COMMIT"
echo "   Files:   $FILE_COUNT .py files"
echo "   Lines:   $LINE_COUNT lines"
echo "   Path:    $VENDOR_DIR"
