#!/usr/bin/env bash
# Pre-push hook: run the Bazel test suite for branch pushes that change Go or
# Bazel inputs (scripts/pre-push-suite.sh), and when pushing a release tag
# (refs/tags/v*), refuse the push if version constants disagree. The version
# check stops a release from being tagged/published with drifted versions (the
# failure mode that left main red after the 1.0.5 release) before it ever
# reaches CI.
#
# Installed via: git config core.hooksPath .githooks
# See also: make install (sets hooksPath automatically)
#
# Bypass (not recommended for release tags): git push --no-verify

set -euo pipefail

# git feeds "<local ref> <local sha> <remote ref> <remote sha>" lines on stdin.
# Capture it so the chained beads hook at the bottom still sees the ref list.
push_refs="$(cat)"

pushing_version_tag=0
while read -r local_ref _local_sha _remote_ref _remote_sha; do
    case "$local_ref" in
        refs/tags/v[0-9]*) pushing_version_tag=1 ;;
    esac
done <<< "$push_refs"

if [ "$pushing_version_tag" -eq 1 ]; then
    repo_root="$(git rev-parse --show-toplevel)"
    # Skip on older checkouts without the consistency check; do not block.
    if [ -x "$repo_root/scripts/check-versions.sh" ]; then
        while read -r local_ref _local_sha _remote_ref _remote_sha; do
            case "$local_ref" in
                refs/tags/v[0-9]*)
                    tag_version="${local_ref#refs/tags/v}"
                    echo "Release tag v$tag_version push detected — verifying version consistency..."
                    checker_status=0
                    (cd "$repo_root" && ./scripts/check-versions.sh --expect "$tag_version") || checker_status=$?
                    if [ "$checker_status" -ne 0 ]; then
                        echo ""
                        if [ "$checker_status" -eq 1 ]; then
                            echo "❌ Refusing to push release tag v$tag_version: versions are inconsistent." >&2
                            echo "   See the checker output above for what is inconsistent and how to fix it." >&2
                        elif [ "$checker_status" -eq 3 ]; then
                            echo "❌ Refusing to push release tag v$tag_version: the tag does not match this checkout's release version." >&2
                            echo "   The release surfaces agree with each other, so do NOT re-run update-versions.sh." >&2
                            echo "   Push only the tag matching this checkout (see CONTRIBUTING.md)." >&2
                        else
                            echo "❌ Refusing to push release tag v$tag_version: version checker unavailable or failed (exit $checker_status)." >&2
                            echo "   Check the Go toolchain and checker diagnostics above." >&2
                        fi
                        echo "   Override with --no-verify only if you know what you are doing." >&2
                        exit 1
                    fi
                    ;;
            esac
        done <<< "$push_refs"
    fi
fi

# The push-time test suite (scripts/pre-push-suite.sh): bazel.yml's test lane,
# `bazel test //... --config=ci`, for branch pushes whose new commits change
# Go or Bazel inputs. A tag push, a deletion, or a docs-only push skips it.
# BD_PREPUSH_SUITE=go runs plain go test instead, under a banner.
#
# The decision keys on the remote ref and the shas, never on the local ref's
# shape: for `git push origin HEAD` and `HEAD:refs/heads/x` git passes the
# literal local ref `HEAD`, which a `refs/heads/*` match would skip (#7351).
zero_sha=0000000000000000000000000000000000000000
suite_needed=0
while read -r _local_ref local_sha remote_ref remote_sha; do
    case "$remote_ref" in
        refs/tags/*) continue ;;
    esac
    if [ "$local_sha" = "$zero_sha" ] || ! git cat-file -e "$local_sha^{commit}" 2>/dev/null; then
        continue
    fi
    base="$remote_sha"
    if [ "$base" = "$zero_sha" ] || ! git cat-file -e "$base^{commit}" 2>/dev/null; then
        # A new remote branch: compare against main's merge-base.
        base="$(git merge-base "$local_sha" origin/main 2>/dev/null || true)"
    fi
    if [ -z "$base" ] || git diff --name-only "$base" "$local_sha" -- \
        '*.go' 'go.mod' 'go.sum' '*.bazel' '*.bzl' '.bazelrc' '.bazelversion' 'MODULE.bazel.lock' | grep -q .; then
        suite_needed=1
    fi
done <<< "$push_refs"

if [ "$suite_needed" -eq 1 ]; then
    repo_root="$(git rev-parse --show-toplevel)"
    "$repo_root/scripts/pre-push-suite.sh" </dev/null
fi

exec < <(printf '%s\n' "$push_refs")

# --- BEGIN BEADS INTEGRATION v1.3.0 ---
# This section is managed by beads. Do not remove these markers.
if command -v bd >/dev/null 2>&1; then
  export BD_GIT_HOOK=1
  _bd_timeout=${BEADS_HOOK_TIMEOUT:-300}
  case "$_bd_timeout" in
    *[!0-9]*|'') _bd_timeout_invalid=1 ;;
    *[1-9]*) _bd_timeout_invalid=0 ;;
    *) _bd_timeout_invalid=1 ;;
  esac
  if [ "$_bd_timeout_invalid" -eq 1 ]; then
    echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds"
    _bd_timeout=300
  fi
  _bd_timeout_backend=none
  _bd_timeout_command=
  for _bd_timeout_candidate in timeout gtimeout; do
    if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then
      if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then
        case "$_bd_timeout_version" in
          "timeout (GNU coreutils) "*|"timeout (uutils coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;;
        esac
      fi
    fi
  done
  if [ -n "$_bd_timeout_command" ]; then
    _bd_timeout_backend=coreutils
    if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run pre-push "$@"; then
      _bd_exit=0
    else
      _bd_exit=$?
    fi
  elif command -v perl >/dev/null 2>&1; then
    _bd_timeout_backend=perl
    if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run pre-push "$@"; then
      _bd_exit=0
    else
      _bd_exit=$?
    fi
  else
    echo >&2 "beads: hook 'pre-push' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT"
    if bd hooks run pre-push "$@"; then
      _bd_exit=0
    else
      _bd_exit=$?
    fi
  fi
  if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then
    echo >&2 "beads: hook 'pre-push' timed out after ${_bd_timeout}s — continuing without beads"
    _bd_exit=0
  fi
  if [ "$_bd_exit" -eq 3 ]; then
    echo >&2 "beads: database not initialized — skipping hook 'pre-push'"
    _bd_exit=0
  fi
  if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi
fi
# --- END BEADS INTEGRATION v1.3.0 ---
