#!/usr/bin/env bash
set -euo pipefail

# Skip the workspace clippy + tests when the push touches only docs/markdown.
# Those checks exist to catch broken Rust code; docs-only changes can't trigger
# that, so the gate adds friction without protection here.
ZERO_SHA="0000000000000000000000000000000000000000"
DOCS_RE='^(README\.md|CHANGELOG\.md|RELEASING\.md|LICENSE|CODE_OF_CONDUCT\.md|CONTRIBUTING\.md|SECURITY\.md|CLAUDE\.md|docs/.*|\.github/.*\.md)$'

all_changed=""
while read -r local_ref local_sha remote_ref remote_sha; do
    [ -z "${local_ref:-}" ] && continue
    [ "$local_sha" = "$ZERO_SHA" ] && continue
    if [ "$remote_sha" = "$ZERO_SHA" ]; then
        base=$(git merge-base "$local_sha" origin/main 2>/dev/null \
            || git rev-list --max-parents=0 "$local_sha" | head -n 1)
    else
        base="$remote_sha"
    fi
    changed=$(git diff --name-only "$base" "$local_sha" 2>/dev/null || true)
    [ -n "$changed" ] && all_changed=$(printf '%s\n%s' "$all_changed" "$changed")
done

all_changed=$(printf '%s' "$all_changed" | sed '/^$/d')

if [ -n "$all_changed" ]; then
    non_docs=$(printf '%s\n' "$all_changed" | grep -vE "$DOCS_RE" || true)
    if [ -z "$non_docs" ]; then
        count=$(printf '%s\n' "$all_changed" | wc -l | tr -d ' ')
        echo "Pre-push: docs-only push ($count file(s)), skipping clippy + tests."
        exit 0
    fi
fi

# Pre-push runs FAST checks: clippy + library tests only. Integration tests
# (crates/origin-core/tests/eval_harness.rs) need the ONNX BGE model and run
# for minutes; they belong in CI. Coverage gates are NOT enforced here either
# — the instrumented `cargo llvm-cov` rebuild can take 5-15min and overload
# memory. Use `bash scripts/coverage.sh` for a local coverage report. See
# CLAUDE.md "Local vs CI test responsibilities".
echo "Pre-push: running fast checks..."

echo "  Running Clippy..."
cargo clippy --workspace --all-targets -- -D warnings 2>&1 || {
    echo "FAIL: Clippy warnings found. Fix before pushing."
    exit 1
}

echo "  Running library tests..."
cargo test --workspace --lib --quiet 2>&1 || {
    echo "FAIL: Library tests failed. Fix before pushing."
    exit 1
}

echo "Pre-push: all fast checks passed. Safe to push (CI runs full suite + coverage)."
