#!/usr/bin/env sh
# Timestamp-aware reimport guard (custom, NOT managed by beads -- lives
# outside the BEGIN/END markers below so `bd hooks install`/upgrades
# cannot regenerate it away). bd's own post-merge reimport is a blind
# upsert with no timestamp comparison, so an ordinary pull/merge can
# silently revert a bead closed-but-uncommitted in a different worktree
# sharing the same live Dolt DB. This wraps the normal hook: snapshot
# live state before it runs, let it run unmodified, then restore
# anything it clobbered with an older value. See
# .agent/scripts/bd-reimport-guard.py docstring for full rationale.
_bd_guard="$(dirname "$0")/../.agent/scripts/bd-reimport-guard.py"
if [ -f "$_bd_guard" ] && command -v python3 >/dev/null 2>&1; then
  python3 "$_bd_guard" snapshot post-merge 2>/dev/null || true
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 post-merge "$@"
    _bd_exit=$?
    if [ $_bd_exit -eq 124 ]; then
      echo >&2 "beads: hook 'post-merge' timed out after ${_bd_timeout}s — continuing without beads"
      _bd_exit=0
    fi
  else
    bd hooks run post-merge "$@"
    _bd_exit=$?
  fi
  if [ $_bd_exit -eq 3 ]; then
    echo >&2 "beads: database not initialized — skipping hook 'post-merge'"
    _bd_exit=0
  fi
  if [ $_bd_exit -ne 0 ]; then exit $_bd_exit; fi
fi
# --- END BEADS INTEGRATION v1.0.4 ---

if [ -f "$_bd_guard" ] && command -v python3 >/dev/null 2>&1; then
  python3 "$_bd_guard" check-and-repair post-merge 2>&1 || true
fi
