#!/usr/bin/env bash
#
# Every document carries a complete, valid status header.
#
# ## Why this is a guard and not a convention
#
# `DOC_TRUST_MAP.md` makes two claims that nothing else enforces: the status
# word is one of exactly four, and `Review trigger` is the line that stops a
# document going quietly stale. A header carrying `Status` without
# `Review trigger` is the specific failure worth catching — it looks finished
# and is not.
#
# This repository is the reason. Before 2026-08-18 it had six markdown documents
# at its root with no headers at all, two of which described the project as
# being in "Phase 5" while the code was at 0.9.3. Nothing said so.
#
# Checked in the first sixteen lines, which is where a header lives.
#
# Exit 0 all conformant, 1 at least one is not, 2 no documents were found —
# which is not a pass, because it is what a moved docs/ directory looks like.
set -uo pipefail
cd "$(git rev-parse --show-toplevel)" || exit 1

VALID="Current Draft Superseded Archived"
bad=0
seen=0

# docs/** at any depth, plus the root one level deep — the same scope
# doc-triggers.py reads, so a document one tool checks the other fires on.
while IFS= read -r f; do
  [ -n "$f" ] || continue
  seen=$((seen + 1))
  head16=$(head -16 "$f")

  status=$(printf '%s\n' "$head16" | sed -nE 's/^Status:[[:space:]]*([A-Za-z]+).*/\1/p' | head -1)
  trigger=$(printf '%s\n' "$head16" | grep -c '^Review trigger:' || true)
  governs=$(printf '%s\n' "$head16" | grep -c '^Governs:' || true)

  if [ -z "$status" ]; then
    echo "no Status in the first 16 lines            $f" >&2; bad=$((bad + 1)); continue
  fi
  case " $VALID " in
    *" $status "*) ;;
    *) echo "Status: '$status' is not one of the four      $f" >&2; bad=$((bad + 1)) ;;
  esac
  [ "$trigger" -ge 1 ] || { echo "Status but no Review trigger — looks done   $f" >&2; bad=$((bad + 1)); }
  [ "$governs" -ge 1 ] || { echo "no Governs: line                           $f" >&2; bad=$((bad + 1)); }
done < <(git ls-files 'docs/**/*.md' 'docs/*.md' '*.md' 2>/dev/null)

if [ "$seen" -eq 0 ]; then
  echo "doc-headers: no tracked markdown found. Nothing was checked — that is not a pass." >&2
  exit 2
fi

if [ "$bad" -gt 0 ]; then
  echo "doc-headers: $bad problem(s) across $seen document(s)." >&2
  exit 1
fi

echo "doc-headers: $seen document(s), all with a valid Status, Governs and Review trigger."
