#!/usr/bin/env sh
# Pre-commit: block accidentally committed secrets.
#
# Uses secretlint against staged files only (fast). If secretlint is not
# installed (e.g. contributor skipped `npm install`), the hook fails open
# with a warning — CI will still run the authoritative check.
#
# To skip this hook locally (NOT recommended): `git commit --no-verify`.

# Collect list of staged files that would be added/modified (exclude deletions)
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACMR)

if [ -z "$STAGED_FILES" ]; then
  exit 0
fi

if ! command -v npx >/dev/null 2>&1; then
  echo "⚠️  husky/pre-commit: npx not found, skipping secret scan"
  exit 0
fi

# Run secretlint on the staged files. --maskSecrets hides any detected values
# from the terminal output so developers don't accidentally copy them.
echo "$STAGED_FILES" | xargs npx --no-install secretlint --maskSecrets
EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
  echo ""
  echo "❌ Secret scanner blocked the commit."
  echo "   If this is a false positive, add the file to .secretlintignore"
  echo "   or the rule to .secretlintrc.json. To bypass (NOT recommended):"
  echo "   git commit --no-verify"
  exit 1
fi
