# Local fallback for solo dev (no CI). On a local `git merge`, infer the
# phase + spec from the most recent commit and emit the marker. CI workflow
# (.github/workflows/post-merge.yml) is the canonical path; this hook is
# best-effort for offline / solo use.

# Only act on the main branch.
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
if [ "$BRANCH" != "main" ]; then
  exit 0
fi

# Read last commit subject to infer phase + spec.
SUBJECT=$(git log -1 --pretty=%s)
SPEC_ID=""
PHASE=""

# `[FEAT-NNN]` or `[NNN-slug]` in subject.
SPEC_ID=$(printf '%s' "$SUBJECT" | sed -nE 's/.*\[([A-Z]+-[0-9]+|[0-9]+-[a-z0-9-]+)\].*/\1/p')

# Phase from commit conventional-type or path prefix.
case "$SUBJECT" in
  *"shared:"*|*"shared("*)  PHASE=shared ;;
  *"api:"*|*"api("*|*"back:"*|*"back("*)   PHASE=back ;;
  *"web:"*|*"web("*|*"front:"*|*"front("*) PHASE=front ;;
esac

if [ -z "$SPEC_ID" ] || [ -z "$PHASE" ]; then
  exit 0
fi

# Find spec dir.
SPEC_DIR=""
if [ -d ".ai/specs/$SPEC_ID" ]; then
  SPEC_DIR=".ai/specs/$SPEC_ID"
else
  for D in .ai/specs/*/; do
    NAME=$(basename "${D%/}")
    case "$NAME" in
      *"$SPEC_ID"*) SPEC_DIR="${D%/}"; break ;;
    esac
  done
fi

[ -z "$SPEC_DIR" ] && exit 0

bash .claude/hooks/post-merge-marker-emit.sh "$SPEC_DIR" "$PHASE" >/dev/null 2>&1 || true

# Optional .done escalation.
if [ -f "$SPEC_DIR/.back_done" ] && [ -f "$SPEC_DIR/.front_done" ] && [ ! -f "$SPEC_DIR/.done" ]; then
  bash .claude/hooks/post-merge-marker-emit.sh "$SPEC_DIR" done >/dev/null 2>&1 || true
fi

# Best-effort board projection (one-way, opt-in). CI is the canonical path;
# this is for solo/offline dev. Cheap-guard on enabled=true so disabled
# projects pay nothing; the script itself also no-ops without NOTION_TOKEN.
if grep -qE '^\s*enabled:\s*true' .ai/config/observability.yaml 2>/dev/null; then
  pnpm observability:sync >/dev/null 2>&1 || true
fi
