#!/usr/bin/env bash
# The documentation gates (build plan §3c, Decision 11). Two tiers, so one session's commit
# cannot fail another's hand-back on something it does not own:
#   FAIL  agents.md over its 140-line budget; a generated block in main/docs/ that differs
#         from a fresh generation; brief.md's NOW-block version or CHANGELOG.md's first
#         versioned heading disagreeing with app/version.py.
#   WARN  (FAIL only with --strict, which Wave 4 and the post-launch sweep run): a prose doc
#         whose named sources have a newer git commit than the doc; .logs/issues.md not swept
#         in 7 days; a handoff entry over 25 non-blank lines.
# Why: the docs structure existed for two weeks without teeth and the handoff became the only
# documentation. Run from anywhere; called by main/check.sh and by the project /checkpoint.
set -uo pipefail
cd "$(dirname "$0")/.."

STRICT=0; QUIET=0
for a in "$@"; do case "$a" in --strict) STRICT=1;; -q|--quiet) QUIET=1;; esac; done
fails=0; warns=0
fail() { echo "FAIL  $*"; fails=$((fails + 1)); }
warn() { if (( STRICT )); then fail "$*"; else (( QUIET )) || echo "warn  $*"; warns=$((warns + 1)); fi; }

# --- FAIL tier -----------------------------------------------------------------------------
n=$(wc -l < agents.md)
(( n > 140 )) && fail "agents.md is $n lines; the budget is 140"

if ! out=$(python3 main/scripts/docmap.py --check 2>&1); then
  fail "a generated block is stale:"; sed 's/^/      /' <<<"$out"
fi

ver=$(sed -nE 's/^APP_VERSION *= *"([^"]+)".*/\1/p' main/app/version.py)
now=$(sed -nE 's/^- \*\*Live version:\*\* *([0-9][^ ]*).*/\1/p' brief.md)
[[ -n "$ver" ]] || fail "could not read APP_VERSION from main/app/version.py"
[[ "$now" == "$ver" ]] || fail "brief.md NOW block says version '${now:-none}'; app/version.py says '$ver'"
cl=$(grep -oE '^## [0-9]+\.[0-9]+\.[0-9]+' main/CHANGELOG.md | head -1 | cut -c4-)
[[ "$cl" == "$ver" ]] || fail "CHANGELOG.md's first versioned heading is '${cl:-none}'; app/version.py says '$ver' (an Unreleased heading above it is fine)"

# --- WARN tier -----------------------------------------------------------------------------
for doc in main/docs/*.md; do
  dt=$(git log -1 --format=%ct -- "$doc" 2>/dev/null); [[ -n "$dt" ]] || continue  # uncommitted: skip
  srcs=$(awk '/^Sources of truth:/{p=1} p&&!NF{exit} p' "$doc" | grep -oE '`[^`]+`' | tr -d '`')
  for s in $srcs; do
    [[ -e "$s" ]] || { warn "$doc names a source that does not exist: $s"; continue; }
    st=$(git log -1 --format=%ct -- "$s" 2>/dev/null); [[ -n "$st" ]] || continue
    (( st > dt )) && warn "$doc is older than its source $s (re-read the source, then update the doc)"
  done
done

sw=$(grep -oiE 'last swept:? *[0-9]{4}-[0-9]{2}-[0-9]{2}' .logs/issues.md | head -1 | grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}')
if [[ -z "$sw" ]]; then
  warn ".logs/issues.md carries no 'last swept <date>' stamp"
else
  age=$(( ( $(date +%s) - $(date -d "$sw" +%s) ) / 86400 ))
  (( age > 7 )) && warn ".logs/issues.md was last swept $sw, $age days ago"
fi

long=$(awk '/^## /{ if (h != "" && n > 25) printf "      %d lines: %s\n", n, h; h = $0; n = 0; next }
            NF { n++ } END { if (h != "" && n > 25) printf "      %d lines: %s\n", n, h }' .logs/handoff.md)
if [[ -n "$long" ]]; then
  warn "handoff entries over 25 lines (explain in main/docs/, then link):"
  if ! (( QUIET )); then
    head -5 <<<"$long"
    (( $(wc -l <<<"$long") > 5 )) && echo "      ... and $(( $(wc -l <<<"$long") - 5 )) more"
  fi
fi

# --- verdict -------------------------------------------------------------------------------
echo "docs-check: $fails fail, $warns warn$( (( STRICT )) && echo ' (strict)')$( (( QUIET && warns )) && echo '; bash main/docs-check.sh lists them')"
(( fails == 0 ))
