#!/usr/bin/env bash
# agentspm pre-commit hook (SEC-D5) — active from the FIRST commit.
# BLOCK: sensitive file names, secret patterns, real identifiers (NFR-D1).
# WARN:  forbidden language patterns (pre-push and CI BLOCK them).
# Install: scripts/setup-hooks.sh  (git config core.hooksPath .githooks)
#
# Note: the secret regexes are written in a self-non-matching form (e.g. a
# character class instead of the final literal character) so that committing
# this hook and the scan config does not trip the scan itself.
set -euo pipefail

mapfile -t STAGED < <(git diff --cached --name-only --diff-filter=ACM)
if [ "${#STAGED[@]}" -eq 0 ]; then
  exit 0
fi

fail=0

# --- 1. sensitive file names (never commit these) ---------------------------
for f in "${STAGED[@]}"; do
  base=$(basename "$f")
  case "$base" in
    .env|.env.local|.env.production)
      echo "BLOCK: sensitive file staged: $f (use .env.example)"; fail=1 ;;
    *.pem|*.key|id_rsa|id_ed25519)
      echo "BLOCK: key material staged: $f"; fail=1 ;;
  esac
done

# --- 2. secret content scan (gitleaks-style) --------------------------------
SECRET_PATTERNS=(
  'AGE-SECRET-KEY-[0-9A-Z]'
  'BEGIN[[:space:]]+[A-Z ]*PRIVATE[[:space:]]+KEY'
  'gw-[A-Za-z0-9]{8,}'
  'AKIA[0-9A-Z]{16}'
  'ssh-rsa[[:space:]]+AAAA'
  "(password|secret|api[_-]?key|token)[[:space:]]*=[[:space:]]*[\"'][^\"']{8,}"
)
for f in "${STAGED[@]}"; do
  # Allowlist (Git Hook Strategy): fixtures carrying an explicit synthetic marker.
  if [[ "$f" == tests/fixtures/* ]] && git show ":$f" 2>/dev/null | grep -q 'synthetic: true'; then
    continue
  fi
  content=$(git show ":$f" 2>/dev/null) || continue
  for pat in "${SECRET_PATTERNS[@]}"; do
    if hits=$(printf '%s\n' "$content" | grep -I -n -E "$pat"); then
      echo "BLOCK: secret-pattern match in $f:"
      echo "$hits" | head -5
      fail=1
    fi
  done
done

# --- 3. identifier scan on staged content (NFR-D1) — BLOCK ------------------
if ! python3 scripts/identifier_scan.py --staged; then
  echo "BLOCK: real identifiers must never enter git history (NFR-D1)."
  fail=1
fi

# --- 4. language lint — WARN at commit (pre-push/CI BLOCK) ------------------
if ! python3 scripts/language_lint.py --staged; then
  echo "WARN: forbidden language patterns in staged files (pre-push will BLOCK)."
fi

if [ "$fail" -ne 0 ]; then
  echo "pre-commit: BLOCKED. Fix the findings above; never bypass with --no-verify."
fi
exit "$fail"
