#!/usr/bin/env bash
#
# pre-push 钩子 —— 推送前质量门禁
#
# 仅在 `git push` 时运行，绝不在 `git commit` 时运行：
# 平时可以自由 commit 保存 WIP，只有真正要推送时才做完整校验。
#
# 校验项与 .github/workflows/ci.yml 的 Test job 完全一致，
# 因此「本地 pre-push 通过」即可推断「CI 也会通过」：
#   1. cargo fmt --all -- --check
#   2. cargo clippy --all-targets --all-features -- -D warnings
#   3. cargo test --all-features
#
# 一次性启用（克隆后执行一次即可）：
#   make hooks            # 等价于 git config core.hooksPath .githooks
#
set -euo pipefail

# 定位仓库根目录，并切换过去运行（无论从哪个子目录触发 push）。
REPO_ROOT="$(git rev-parse --show-toplevel)"
cd "$REPO_ROOT"

echo "==> [pre-push] 开始推送前校验（fmt → clippy → test）..."

# ── 1. 格式检查 ──────────────────────────────────────────────
echo "==> [1/3] cargo fmt --all -- --check"
if ! cargo fmt --all -- --check; then
    echo "" >&2
    echo "❌ 格式检查失败：代码未通过 rustfmt 校验。" >&2
    echo "   请运行  cargo fmt --all  自动格式化后重新提交，再推送。" >&2
    echo "   推送已中止。" >&2
    exit 1
fi

# ── 2. Clippy 静态检查 ───────────────────────────────────────
echo "==> [2/3] cargo clippy --all-targets --all-features -- -D warnings"
if ! cargo clippy --all-targets --all-features -- -D warnings; then
    echo "" >&2
    echo "❌ Clippy 检查失败：存在被视为错误的 lint 警告（-D warnings）。" >&2
    echo "   请根据上方 clippy 输出修复所有警告后重新提交，再推送。" >&2
    echo "   推送已中止。" >&2
    exit 1
fi

# ── 3. 测试 ──────────────────────────────────────────────────
echo "==> [3/3] cargo test --all-features"
if ! cargo test --all-features; then
    echo "" >&2
    echo "❌ 测试失败：cargo test --all-features 未全部通过。" >&2
    echo "   请修复失败的测试后重新提交，再推送。" >&2
    echo "   推送已中止。" >&2
    exit 1
fi

echo "==> [pre-push] ✅ 全部校验通过，允许推送。"
exit 0
