#!/usr/bin/env bash
# Pre-commit hook: Definition of Done (fast lane) + checkpoint verification
#
# This hook runs the fast lane definition-of-done checks before allowing a commit.
# It counts bypasses so we know when quality gates are being skipped.
#
# To bypass this hook (NOT RECOMMENDED), use:
#   git commit --no-verify -m "..."
# This will be recorded in .beads/bypasses.jsonl by the post-commit hook.

set -euo pipefail

repo_root="$(git rev-parse --show-toplevel)"
cd "$repo_root"

# shellcheck source=../scripts/bypass-detection.sh
source "$repo_root/scripts/bypass-detection.sh"

echo "=== Running Definition of Done (fast lane, this commit's paths) ==="

# --changed-only: this checkout is shared with other workers, so the tree
# routinely contains somebody else's half-finished file. Without it the hook
# fails for reasons the committer did not cause and cannot fix without editing
# in-flight work that is not theirs, and the only way out is --no-verify —
# which is how .beads/bypasses.jsonl reached 607 entries. A pre-existing
# failure elsewhere is still printed in full; it just does not block.
export NEEDLE_PRE_COMMIT=1
if ! scripts/definition-of-done.sh --fast --count-bypass --changed-only; then
  echo ""
  echo "❌ Pre-commit check failed"
  echo ""
  echo "Your changes do not meet the Definition of Done."
  echo "Please fix the issues above before committing."
  echo ""
  echo "Every failure listed above is in a file THIS commit stages — the lane"
  echo "no longer blocks on other workers' in-flight files, so this is yours."
  echo ""
  echo "To bypass (not recommended), use: git commit --no-verify"
  echo "This is recorded in .beads/bypasses.jsonl, and the DoD-bypass check in"
  echo "the outcome handler fails the dispatch of any bead whose commit is there."
  exit 1
fi

echo "=== Running secret verification ==="
if ! "$repo_root/scripts/secret-scan.sh" staged; then
  needle_clear_index_state
  exit 1
fi

echo "=== Running checkpoint verification ==="
if ! "$repo_root/scripts/checkpoint-publish.sh" verify-index; then
  # Do not leave an environment-bypass marker behind if this later hook check
  # prevents the commit from being created.
  needle_clear_index_state
  exit 1
fi
