#!/usr/bin/env bash
# Bloque `git commit` si le message ne suit pas Conventional Commits.
# Supporte: -m "msg", -m 'msg', heredoc $(cat <<'EOF' ... EOF).
# Passe sans bloquer pour les commits interactifs, -F, --amend sans -m, merge, revert.

set -euo pipefail

CONVENTIONAL_RE='^(feat|fix|chore|docs|refactor|test|style|perf|build|ci|revert)(\([^)]+\))?!?: .+'

input="$(cat)"
command="$(printf '%s' "$input" | jq -r '.tool_input.command // ""')"

case "$command" in
  *"git commit"*) ;;
  *) exit 0 ;;
esac

msg=""

if printf '%s' "$command" | grep -q "<<'\?EOF'\?"; then
  msg="$(printf '%s' "$command" | awk "/<<'?EOF'?/{flag=1;next} flag && NF{print; exit}")"
fi

if [ -z "$msg" ]; then
  msg="$(printf '%s' "$command" | sed -nE 's/.*-m[[:space:]]+"([^"]+)".*/\1/p' | head -1)"
fi
if [ -z "$msg" ]; then
  msg="$(printf '%s' "$command" | sed -nE "s/.*-m[[:space:]]+'([^']+)'.*/\1/p" | head -1)"
fi

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

case "$msg" in
  "Merge "*|"Revert "*) exit 0 ;;
esac

if ! printf '%s' "$msg" | grep -qE "$CONVENTIONAL_RE"; then
  cat >&2 <<EOF
[hook] Commit bloqué : message non conforme à Conventional Commits.

Format requis : <type>(<scope>)?!?: <description>
Types : feat, fix, chore, docs, refactor, test, style, perf, build, ci, revert

Reçu :
  $msg
EOF
  exit 2
fi

exit 0
