#!/bin/bash
# ═══════════════════════════════════════════════════════════
# 光湖语言系统 · 一键安装 pre-push-clean 插件
# 在任意光湖仓库根目录下执行本脚本即可
#
# 用法: bash zero-point/core-channel/revive-guard/install-hooks.sh
# ═══════════════════════════════════════════════════════════

set -e

REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
if [ -z "$REPO_ROOT" ]; then
    echo "❌ 请在 git 仓库根目录下执行本脚本"
    exit 1
fi

HOOK_DIR="$REPO_ROOT/.git/hooks"
PLUGIN_SRC="$REPO_ROOT/zero-point/core-channel/revive-guard/pre-push-clean.py"
NAVIGATION_GUARD_SRC="$REPO_ROOT/zero-point/core-channel/revive-guard/navigation-memory-guard.py"
PLUGIN_DST="$HOOK_DIR/pre-push"
NAVIGATION_GUARD_DST="$HOOK_DIR/navigation-memory-guard.py"

echo "🛡️  光湖 pre-push-clean 插件安装"
echo "   仓库: $(basename "$REPO_ROOT")"
echo ""

# 1. 检查源文件
if [ ! -f "$PLUGIN_SRC" ] || [ ! -f "$NAVIGATION_GUARD_SRC" ]; then
    echo "❌ 找不到 $PLUGIN_SRC"
    echo "   请确保在 fifth-domain 仓库根目录下执行"
    exit 1
fi

# 2. 创建钩子目录
mkdir -p "$HOOK_DIR"

# 3. 备份旧钩子（如果存在且不是我们的）
if [ -f "$PLUGIN_DST" ] && ! grep -q "pre-push-clean" "$PLUGIN_DST" 2>/dev/null; then
    BACKUP="$PLUGIN_DST.backup.$(date +%Y%m%d%H%M%S)"
    cp "$PLUGIN_DST" "$BACKUP"
    echo "   ⚠️  旧 pre-push 钩子已备份到 $BACKUP"
fi

# 4. 安装插件
cp "$PLUGIN_SRC" "$PLUGIN_DST"
chmod +x "$PLUGIN_DST"
cp "$NAVIGATION_GUARD_SRC" "$NAVIGATION_GUARD_DST"
chmod +x "$NAVIGATION_GUARD_DST"

# 5. 验证
echo ""
echo "   验证安装..."
if python3 "$PLUGIN_DST" --check; then
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "  ✅ 安装完成!"
    echo ""
    echo "  现在每次 git push 前都会自动:"
    echo "    ① 扫描待推送内容"
    echo "    ② 检测敏感信息（邮箱/密码/token）"
    echo "    ③ 自动替换为 REDACTED 乱码"
    echo "    ④ 加 [SEC-CLEAN] 标记"
    echo "    ⑤ 继续正常推送"
    echo ""
    echo "  你什么都不用做。正常 git push 就行。"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
else
    echo "❌ 验证失败，请检查 Python3 是否可用"
    exit 1
fi
