#!/usr/bin/env bash
# Git pre-push hook — installed by `just install-hooks` (or `just setup`).
#
# Runs `just check` before any branch push reaches the remote. This is the
# tool-agnostic backstop: it fires whether the push comes from a human shell,
# Claude Code, Gemini CLI, or any other tool.
#
# Escape hatch (human emergency use only): GIT_NO_CHECK=1 git push

set -euo pipefail

if [ "${GIT_NO_CHECK:-0}" = "1" ]; then
    echo "[pre-push] GIT_NO_CHECK=1 set — skipping pre-push checks." >&2
    exit 0
fi

# Read the ref tuples git passes on stdin:
#   <local ref> <local oid> <remote ref> <remote oid>
# Skip the check when every ref in this push is either a branch deletion
# (local oid is all zeros — e.g. `gh pr merge --delete-branch` inside
# `just merge-pr`) or a push to `gh-pages`.
ZERO_OID="0000000000000000000000000000000000000000"
NEEDS_CHECK=0
SAW_REFS=0
while read -r _local_ref local_oid remote_ref _remote_oid; do
    [ -z "${local_oid:-}" ] && continue
    SAW_REFS=1
    if [ "$local_oid" = "$ZERO_OID" ]; then
        continue
    fi
    if [ "$remote_ref" = "refs/heads/gh-pages" ]; then
        continue
    fi
    NEEDS_CHECK=1
done

if [ "$SAW_REFS" = "1" ] && [ "$NEEDS_CHECK" = "0" ]; then
    exit 0
fi

if ! command -v just >/dev/null 2>&1; then
    echo "ERROR [pre-push]: 'just' is not on PATH; cannot run pre-push gate." >&2
    exit 1
fi

REPO_ROOT="$(git rev-parse --show-toplevel)"
echo "[pre-push] Running 'just check'..." >&2
just --justfile "$REPO_ROOT/Justfile" --working-directory "$REPO_ROOT" check
