#!/usr/bin/env bash
# Pre-push gate: quick verification baseline (format + lint only).
# Full verification (mypy, render all, pytest) is expected to have already
# run via `devtools verify` before the push (see CONTRIBUTING.md).
# CI runs the complete baseline.
#
# When `devtools verify` completed successfully at the current HEAD, the
# stamp file at .cache/last-verify-head matches and this hook is a no-op.

set -euo pipefail

# Pre-flight: ensure checkout-local devtools is importable before attempting verification.
if ! python -m devtools --help >/dev/null 2>&1; then
    echo "pre-push: checkout-local devtools is not importable; enter the project devshell (nix develop) first." >&2
    exit 2
fi

STAMP_FILE=".cache/last-verify-head"

if [[ -f "$STAMP_FILE" ]]; then
    STAMPED=$(head -n1 "$STAMP_FILE")
    CURRENT=$(git rev-parse HEAD)
    if [[ "$STAMPED" == "$CURRENT" ]]; then
        echo "pre-push: HEAD already verified (${STAMPED:0:8}); skipping." >&2
    else
        echo "pre-push: HEAD changed since last verify; running gate." >&2
        echo "pre-push: running quick verification baseline" >&2
        python -m devtools verify --quick
    fi
else
    echo "pre-push: running quick verification baseline" >&2
    python -m devtools verify --quick
fi

# --- BEGIN BEADS INTEGRATION v1.0.4 ---
# 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}
  if command -v timeout >/dev/null 2>&1; then
    timeout "$_bd_timeout" bd hooks run pre-push "$@"
    _bd_exit=$?
    if [ $_bd_exit -eq 124 ]; then
      echo >&2 "beads: hook 'pre-push' timed out after ${_bd_timeout}s — continuing without beads"
      _bd_exit=0
    fi
  else
    bd hooks run pre-push "$@"
    _bd_exit=$?
  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.0.4 ---
