#!/usr/bin/env bash
# Pre-push hook: when pushing a release tag (refs/tags/v*), refuse the push if
# version constants disagree. This 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

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 ---
