#!/usr/bin/env bash
# What CI runs anyway; better to find out before the round trip.
set -uo pipefail
# git passes one "<local ref> <local oid> <remote ref> <remote oid>" line per pushed ref;
# read it before anything else can consume stdin.
updates=$(cat)
cd "$(git rev-parse --show-toplevel)" || exit 1
fail=0

echo "pre-push: tests"
uv run pytest -q || fail=1

echo "pre-push: types"
# ci_doctor only, matching the CI job — tests are not type-checked.
uv run ty check ci_doctor || fail=1

# The commit-msg hook is skipped by --no-verify, rebases and web edits; this catches what
# slipped past. Single-commit PRs default their title to the commit subject. Only commits
# the remote doesn't have yet: what's already pushed can't be fixed here.
echo "pre-push: commits"
if command -v commitlint >/dev/null 2>&1; then
  zero=$(git hash-object --stdin </dev/null | tr '0-9a-f' '0')
  while read -r _ local_oid _ remote_oid; do
    [[ -z "$local_oid" || "$local_oid" == "$zero" ]] && continue  # nothing to push, or a delete
    if [[ "$remote_oid" == "$zero" ]]; then
      range=("$local_oid" --not "--remotes=$1")  # a new branch: what no remote branch has
    else
      range=("$remote_oid..$local_oid")
    fi
    for c in $(git rev-list "${range[@]}"); do
      git log -1 --format=%B "$c" | commitlint || fail=1
    done
  done <<<"$updates"
else
  echo "pre-push: commits (skipped — commitlint not installed; \`mise install\`)"
fi

# Optional: only runs if you have it. mise install puts it on PATH.
if command -v gitleaks >/dev/null 2>&1; then
  echo "pre-push: leaks"
  gitleaks git --no-banner --redact || fail=1
else
  echo "pre-push: leaks (skipped — gitleaks not installed; \`mise install\`)"
fi

[[ $fail -eq 0 ]] || echo "pre-push: blocked. Use --no-verify only if you mean it." >&2
exit $fail
