#!/usr/bin/env bash
# pre-push — gate release tags AND mirror CI's lint job. Blocks `git push` of a v* tag unless
# release-preflight passes, and blocks any branch push that would fail CI's ruff check/format
# (the #1 source of red-CI emails: a push that lints clean locally but was never checked).
#
# Enable once per clone:   git config core.hooksPath .githooks
# Override in a pinch:      git push --no-verify   (skips ALL pre-push hooks — use sparingly)
#
# Args: $1 = remote name, $2 = remote url.  stdin lines: <local ref> <local sha> <remote ref> <remote sha>
set -euo pipefail
remote="${1:-origin}"
root="$(git rev-parse --show-toplevel)"

status=0
lint_ran=0
while read -r local_ref _ _ _; do
  case "$local_ref" in
    refs/tags/v[0-9]*)
      tag="${local_ref#refs/tags/}"
      echo "pre-push: verifying release $tag → $remote"
      if ! bash "$root/scripts/release-preflight.sh" "$tag"; then
        echo "pre-push: release preflight failed — push aborted. Fix the above, or 'git push --no-verify' to override." >&2
        status=1
      fi
      ;;
    refs/heads/*)
      if [ "$lint_ran" -eq 0 ]; then
        lint_ran=1
        echo "pre-push: ruff check + format (mirrors CI lint)"
        if ! (cd "$root" && uvx ruff check . && uvx ruff format --check .); then
          echo "pre-push: ruff failed — push aborted (CI lint would go red). Run 'uvx ruff check --fix . && uvx ruff format .', commit, retry." >&2
          status=1
        fi
      fi
      ;;
  esac
done
exit $status
