#!/usr/bin/env bash
# adapters/wordpress/hooks/commit-msg — WordPress adapter overlay
#
# Appended below the core commit-msg by `phaseops init` when the
# WordPress adapter is enabled. Reproduces the upstream slice-trailer guard: when an
# active phase state file exists, the commit subject must contain
# "Phase [A-Z]+" somewhere on the line.
#
# Maps the upstream .wp-fleet-phase-*-state.json to the PhaseOps
# canonical .phaseops/state/active.json. Detects the phase from the
# JSON `phase` field; enforcement only fires when a phase is active.
#
# Escape hatch: PHASEOPS_WP_NO_PHASE_ENFORCEMENT=1 git commit ...

set -euo pipefail

if [ "${PHASEOPS_WP_NO_PHASE_ENFORCEMENT:-0}" = "1" ]; then
  exit 0
fi

msg_file="${1:-}"
[ -z "$msg_file" ] && exit 0
[ ! -f "$msg_file" ] && exit 0

subject=$(awk 'BEGIN{found=0} /^[^#]/ && NF>0 && !found {print; found=1}' "$msg_file")
case "$subject" in
  "Merge "*) exit 0 ;;
  "Revert "*) exit 0 ;;
esac

STATE_FILE=".phaseops/state/active.json"
[ ! -f "$STATE_FILE" ] && exit 0

active_phase=$(awk -F'"' '/"phase"[[:space:]]*:/ {print $4; exit}' "$STATE_FILE")
[ -z "$active_phase" ] && exit 0

if echo "$subject" | grep -E "Phase[[:space:]]+[A-Z]+" >/dev/null 2>&1; then
  exit 0
fi

echo "ERROR [wordpress]: commit subject must reference an active phase." >&2
echo "  Active phase: $active_phase" >&2
echo "  Subject:      $subject" >&2
echo "  Expected:     '... — Phase [LETTER] [SLICE-ID]'" >&2
echo "  Override:     PHASEOPS_WP_NO_PHASE_ENFORCEMENT=1 git commit ..." >&2
exit 1
