#!/usr/bin/env bash
# managed-by: hone — DO NOT EDIT (run `hone install-hooks --uninstall` to remove)
#
# Hone pre-push hook (HC-001).
# For the current branch's story (if any), assert that for every step marked
# `completed` in metadata.yml, the corresponding step-N artifact file exists.
# Catches the failure mode where a step is marked done in metadata but the
# artifact wasn't committed (would block PR review).
#
# Bypass: HONE_PREPUSH_SKIP=1 git push   (use sparingly per E13-A-L3)
# Thorough: HONE_PREPUSH_THOROUGH=1 git push   (also runs the story's regression tests)

set -euo pipefail

if [ "${HONE_PREPUSH_SKIP:-0}" = "1" ]; then
  echo "⚠ hone pre-push: HONE_PREPUSH_SKIP=1 — skipping (per E13-A-L3, bypass should be rare and tracked)" >&2
  exit 0
fi

BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)"
SKIP_BRANCHES_RE="${HONE_PREPUSH_SKIP_BRANCHES:-^(develop|main|master|release/.*)$}"
if echo "$BRANCH" | grep -qE "$SKIP_BRANCHES_RE"; then
  exit 0
fi

# Extract story ID from branch name (matches SC-NNN, H-NNN, RP-NNN, AU-NNN, SR-NNN, HC-NNN, E-NNN-X)
STORY_ID="$(echo "$BRANCH" | grep -oE '(SC|H|RP|AU|SR|HC|LC|SA)-[0-9]+[A-Z]?|E[0-9]+-[A-Z]' | head -1 || true)"
if [ -z "$STORY_ID" ]; then
  exit 0  # Not a story branch
fi

META=".github/pipeline/$STORY_ID/metadata.yml"
if [ ! -f "$META" ]; then
  exit 0  # Story branch but no metadata yet; pre-commit warned
fi

# Walk completed steps; assert artifact files exist
EXIT_CODE=0
# Read step IDs whose status is "completed" (or "complete")
COMPLETED_STEPS="$(grep -oE 'step_[0-9]+[a-z]?:[[:space:]]*\{[[:space:]]*status:[[:space:]]*(completed|complete)' "$META" | grep -oE 'step_[0-9]+[a-z]?' || true)"

for STEP in $COMPLETED_STEPS; do
  # Find the artifact path: artifact: <name>.md
  ARTIFACT_LINE="$(grep -E "^[[:space:]]+${STEP}:[[:space:]]*\{" "$META" || true)"
  ARTIFACT="$(echo "$ARTIFACT_LINE" | grep -oE 'artifact:[[:space:]]*[a-zA-Z0-9_.-]+' | sed -E 's|artifact:[[:space:]]*||' || true)"
  if [ -n "$ARTIFACT" ]; then
    ARTIFACT_PATH=".github/pipeline/$STORY_ID/$ARTIFACT"
    if [ ! -f "$ARTIFACT_PATH" ]; then
      echo "✗ hone pre-push: $STEP marked completed but artifact $ARTIFACT_PATH is missing" >&2
      EXIT_CODE=1
    fi
  fi
done

# Thorough mode: run the story's regression tests
if [ "${HONE_PREPUSH_THOROUGH:-0}" = "1" ]; then
  TEST_PATTERN="tests/regression/${STORY_ID}-*.test.js"
  if compgen -G "$TEST_PATTERN" > /dev/null; then
    echo "hone pre-push (thorough): running $TEST_PATTERN" >&2
    if ! node --test $TEST_PATTERN 2>&1 | tail -10; then
      EXIT_CODE=1
    fi
  fi
fi

if [ "$EXIT_CODE" -ne 0 ]; then
  echo "" >&2
  echo "✗ hone pre-push: artifact / test gate failed. Fix above OR run with HONE_PREPUSH_SKIP=1 (tracked per E13-A-L3)." >&2
  exit 1
fi

exit 0
