#!/usr/bin/env sh

# Resolve the repo root so the patterns file is found regardless of where the
# hook runs from. Prefer a project-root secrets-patterns.txt (written by
# `npx @settlin/standards init`), else fall back to the one shipped in
# node_modules.
ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo ".")
PATTERNS="$ROOT/secrets-patterns.txt"
if [ ! -f "$PATTERNS" ]; then
  PATTERNS="$ROOT/node_modules/@settlin/standards/secrets-patterns.txt"
fi

# Secrets scan on staged changes. Strip comment/blank lines from the patterns
# file first — grep -f treats every line (including '# AWS') as a regex, which
# would otherwise match the comments themselves.
if [ -f "$PATTERNS" ]; then
  CLEAN=$(grep -vE '^[[:space:]]*#|^[[:space:]]*$' "$PATTERNS")
  if [ -n "$CLEAN" ]; then
    SECRETS=$(git diff --cached -U0 | grep -E "$CLEAN" 2>/dev/null)
    if [ -n "$SECRETS" ]; then
      echo "❌  Possible secrets detected in staged changes:"
      echo "$SECRETS"
      echo ""
      echo "Review the matches above. If they are false positives, remove the"
      echo "matching lines or run 'git commit --no-verify' to bypass (use sparingly)."
      exit 1
    fi
  fi
fi

# Run lint-staged (use bunx if available, else npx)
if command -v bunx >/dev/null 2>&1; then
  bunx lint-staged
else
  npx lint-staged
fi
