#!/usr/bin/env sh

# Fast pre-commit checks (<10s): auto-format staged files, format
# verification, lint, type-check.
#
# Auto-write+re-stage contract per ADR-0016 (supersedes ADR-0013):
# the hook formats staged files via `prettier --write --ignore-unknown`
# and re-stages them via `git add` BEFORE the commit completes, so the
# formatted output lands IN the commit. The working tree is clean
# post-commit; no unstaged prettier deltas (the failure mode P003
# captured and ADR-0013 originally guarded against).
#
# Scope is the staged file set only — never the wider tree. Files
# prettier does not recognise are silently skipped via --ignore-unknown;
# files in .prettierignore are silently skipped by prettier's default
# ignore-file handling.

staged=$(git diff --cached --name-only --diff-filter=ACM)
if [ -n "$staged" ]; then
  echo "$staged" | xargs npx prettier --write --ignore-unknown
  echo "$staged" | xargs git add
fi

# Defense-in-depth: confirm the (now auto-formatted) tree passes the
# read-only check. After --write + re-stage this should always pass;
# failure here indicates a prettier parse error, a config drift, or an
# unformatted file outside the staged set picked up by `prettier --check .`
# (which scans the whole tree per .prettierignore).
if ! npm run format:check; then
  echo "" >&2
  echo "Pre-commit aborted: prettier format:check failed AFTER auto-write." >&2
  echo "This indicates either a prettier parse error in a staged file, a" >&2
  echo "config drift, or an unformatted file outside the staged set." >&2
  echo "Run \`npm run format\` to fix the wider tree, then re-stage and commit again." >&2
  exit 1
fi

npm run lint
npm run type-check
