#!/usr/bin/env sh

# Catalog pre-commit guard. For each rule catalog (business-rules, harness-rules):
# when staged catalog markdown changes, regenerate the index, stage the
# regenerated artifacts into the same commit, then validate the catalog.
# Generate keeps the *-index.json in sync with the source markdown; validate
# catches semantic/structural errors (invalid Estado/Severidad, missing
# Implementa paths, etc.) that generate alone does not catch.
#
# Exit semantics (unchanged): generate failure or validate exit 1 aborts the
# commit; validate exit 2 (warnings only, e.g. paths inexistentes en Implementa)
# does NOT block. `exit 1` inside this function aborts the whole hook because the
# function is called at top level (not in a subshell/pipe), so the exit
# propagates.
#
# Args: $1 human name  $2 diff-filter grep -E pattern  $3 generate script
#       $4 validate script  $5 json artifact  $6 md artifact
run_catalog() {
  name="$1"
  pattern="$2"
  generate_cmd="$3"
  validate_cmd="$4"
  json_artifact="$5"
  md_artifact="$6"

  changed=$(git diff --cached --name-only --diff-filter=ACMR | grep -E "$pattern" || true)

  if [ -n "$changed" ]; then
    echo "› $name: detectados cambios en el catálogo, regenerando índice…"
    if ! pnpm --silent "$generate_cmd"; then
      echo "✗ $name: la regeneración del índice falló."
      echo "  Revisa los errores anteriores y corrige el catálogo antes de volver a commitear."
      exit 1
    fi
    # Stage the regenerated artifacts so they are part of the same commit.
    git add "$json_artifact" "$md_artifact"
    echo "✓ $name: índice regenerado y añadido al commit."

    echo "› $name: validando catálogo…"
    validate_exit=0
    pnpm --silent "$validate_cmd" || validate_exit=$?
    if [ "$validate_exit" = "1" ]; then
      echo "✗ $name: validación falló con errores estructurales."
      echo "  Corrige los errores reportados arriba y vuelve a commitear."
      exit 1
    fi
    # Exit code 2 = warnings only (e.g., paths inexistentes en Implementa). No bloquea.
    echo "✓ $name: catálogo válido."
  fi
}

# Business rules: cliter/<bc>/business-rules/*.md
run_catalog 'business-rules' '^cliter/[^/]+/business-rules/.*\.md$' 'br:generate' 'br:validate' 'cliter/business-rules-index.json' 'docs/business-rules/INDEX.md'

# Harness rules: cliter/harness-rules/*.md (core scope) or cliter/<bc>/harness-rules/*.md (bc-bound / multi-bc)
run_catalog 'harness-rules' '^cliter/harness-rules/.*\.md$|^cliter/[^/]+/harness-rules/.*\.md$' 'hr:generate' 'hr:validate' 'cliter/harness-rules-index.json' 'docs/harness-rules/INDEX.md'
