#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

# Protected-branch commit guard (git-native, defense-in-depth).
#
# The Claude PreToolUse hook (.claude/hooks/branch-guard.sh) also blocks commits on
# protected branches, but it parses the command string and can miss commits whose
# message breaks its regex extraction (multi-line / embedded quotes). This git-level
# guard fires for EVERY commit regardless of how it is invoked.
#
# Exceptions: a merge in progress (.git/MERGE_HEAD), or ALLOW_PROTECTED_COMMIT=1 for
# explicitly approved release automation.
PROTECTED_BRANCH=$(git branch --show-current 2>/dev/null || echo "")
if [ "${ALLOW_PROTECTED_COMMIT:-0}" != "1" ] && [ ! -f "$(git rev-parse --git-dir)/MERGE_HEAD" ]; then
  case "$PROTECTED_BRANCH" in
    main | master | develop)
      echo "[pre-commit] Blocked: cannot commit directly to protected branch '$PROTECTED_BRANCH'." >&2
      echo "[pre-commit] Create a feature branch first: git checkout -b <type>/<scope>-<desc>" >&2
      echo "[pre-commit] Override for approved release automation: ALLOW_PROTECTED_COMMIT=1" >&2
      exit 1
      ;;
  esac
fi

# Auto-generated learning-artifact guard (git-branch.md — lessons are regenerated churn, not
# hand-authored content). Block a commit that STAGES `.agents/evals/lessons/*` — these files are
# regenerated in place and must never be swept into a feature/spec commit via a broad `git add`.
# A sanctioned harness process that intentionally updates them sets ALLOW_LESSONS_COMMIT=1.
if [ "${ALLOW_LESSONS_COMMIT:-0}" != "1" ]; then
  STAGED_LESSONS=$(git diff --cached --name-only | grep -E '^\.agents/evals/lessons/' || true)
  if [ -n "$STAGED_LESSONS" ]; then
    echo "[pre-commit] Blocked: auto-generated lessons are staged (do not commit them):" >&2
    echo "$STAGED_LESSONS" | sed 's/^/[pre-commit]   /' >&2
    echo "[pre-commit] Unstage them (regenerated churn): git restore --staged .agents/evals/lessons" >&2
    echo "[pre-commit] Stage explicit paths, not a broad 'git add .agents'. (git-branch.md)" >&2
    echo "[pre-commit] Sanctioned harness update only: ALLOW_LESSONS_COMMIT=1 git commit ..." >&2
    exit 1
  fi
fi

# `lint:fix:staged` owns the one clone-wide lock around lint-staged. Keeping that ownership in the
# root developer command makes the deliberate pre-verification run and this commit-time safety net
# execute the same path without nesting `flock`. (INFRA-082, INFRA-089)
NODE_OPTIONS="--max-old-space-size=8192" pnpm lint:fix:staged
