#!/usr/bin/env sh
# --- BEGIN BEADS INTEGRATION v1.0.3 ---
# 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-commit "$@"
    _bd_exit=$?
    if [ $_bd_exit -eq 124 ]; then
      echo >&2 "beads: hook 'pre-commit' timed out after ${_bd_timeout}s — continuing without beads"
      _bd_exit=0
    fi
  else
    bd hooks run pre-commit "$@"
    _bd_exit=$?
  fi
  if [ $_bd_exit -eq 3 ]; then
    echo >&2 "beads: database not initialized — skipping hook 'pre-commit'"
    _bd_exit=0
  fi
  if [ $_bd_exit -ne 0 ]; then exit $_bd_exit; fi
fi
# --- END BEADS INTEGRATION v1.0.3 ---

# --- prettier on staged files (outside beads-managed section) -----------------
# Formats only fully-staged files so the formatting lands inside this commit.
# Never blocks the commit: failures are ignored, partially-staged files are
# skipped (formatting + re-adding them would stage hunks you left unstaged).
if [ ! -f "$(git rev-parse --git-dir)/MERGE_HEAD" ] && [ -x ./node_modules/.bin/prettier ]; then
  _staged=$(git diff --cached --name-only --diff-filter=ACMR)
  if [ -n "$_staged" ]; then
    _fmt=""
    _oldifs=$IFS
    IFS='
'
    for _f in $_staged; do
      # fully staged = no unstaged diff for this path
      if git diff --quiet -- "$_f" 2>/dev/null; then
        _fmt="$_fmt$_f
"
      fi
    done
    if [ -n "$_fmt" ]; then
      printf '%s' "$_fmt" | tr '\n' '\0' |
        xargs -0 ./node_modules/.bin/prettier --write --ignore-unknown --log-level silent 2>/dev/null
      printf '%s' "$_fmt" | tr '\n' '\0' | xargs -0 git add -- 2>/dev/null
    fi
    IFS=$_oldifs
  fi
fi
# --- end prettier section -----------------------------------------------------
