#!/usr/bin/env sh
# InboxIntel pre-commit hook — fast checks only (keep it under a few seconds).
# Heavier build/test verification runs in pre-push. Bypass in an emergency with:
#   git commit --no-verify
set -eu

echo "[pre-commit] running fast checks..."

# 1) Block obvious secrets from being committed. Scans only staged, added lines.
STAGED=$(git diff --cached --name-only --diff-filter=ACM)
if [ -n "$STAGED" ]; then
  # Never allow a real .env (only *.example templates are tracked).
  echo "$STAGED" | grep -E '(^|/)\.env($|\.)' | grep -v '\.example$' >/tmp/ii_env_hits 2>/dev/null || true
  if [ -s /tmp/ii_env_hits ]; then
    echo "[pre-commit] BLOCKED: attempting to commit an env/secret file:"
    cat /tmp/ii_env_hits
    echo "  -> add it to .gitignore or commit .env.example instead."
    exit 1
  fi

  # Heuristic secret scan on added lines (private keys, obvious credential assigns).
  if git diff --cached --unified=0 -- $STAGED \
      | grep -E '^\+' \
      | grep -Ei 'BEGIN (RSA|OPENSSH|EC|PGP) PRIVATE KEY|(client_secret|password|api[_-]?key|secret)\s*[:=]\s*["'"'"']?[A-Za-z0-9/_+=-]{16,}' \
      | grep -Evi 'change-me|your-|example|placeholder|\$\{' >/tmp/ii_secret_hits 2>/dev/null; then
    echo "[pre-commit] BLOCKED: possible hard-coded secret in staged changes:"
    cat /tmp/ii_secret_hits
    echo "  -> use deploy/.env / user-secrets. Override with 'git commit --no-verify' if this is a false positive."
    exit 1
  fi
fi

# 2) Format .NET code (only if the tool + staged .cs files are present). Verify-only,
#    non-mutating, so it never rewrites files out from under your staged diff.
if echo "$STAGED" | grep -q '\.cs$'; then
  if command -v dotnet >/dev/null 2>&1 && dotnet format --help >/dev/null 2>&1; then
    echo "[pre-commit] dotnet format --verify-no-changes"
    dotnet format InboxIntel.sln --verify-no-changes --verbosity quiet \
      || { echo "  -> run 'dotnet format InboxIntel.sln' and re-stage."; exit 1; }
  fi
fi

echo "[pre-commit] OK"
