#!/usr/bin/env bash
#
# Report the LLM wiki pages whose covered source has changed since the page was last
# verified. The weekly documentation review starts here instead of re-reading every page.
#
# Each page under docs/wiki/ carries a header comment:
#
#     <!--
#         covers: models services modules/admin
#         verified: <commit-ish>
#     -->
#
# Exit code: 0 when every page is current, 1 when any page is stale or its header is
# missing or unusable.

set -uo pipefail

cd "$( dirname "${BASH_SOURCE[0]}" )/.." || exit 1

status=0

for page in docs/wiki/*.md; do

	name=$( basename "$page" )
	covers=$( sed -n 's/^[[:space:]]*covers:[[:space:]]*//p' "$page" | head -1 )
	verified=$( sed -n 's/^[[:space:]]*verified:[[:space:]]*//p' "$page" | head -1 )

	if [ -z "$covers" ] || [ -z "$verified" ]; then
		printf 'BROKEN %-26s no covers/verified header\n' "$name"
		status=1
		continue
	fi

	if ! git rev-parse --quiet --verify "$verified^{commit}" > /dev/null 2>&1; then
		printf 'BROKEN %-26s unknown commit: %s\n' "$name" "$verified"
		status=1
		continue
	fi

	# Deliberately unquoted: covers is a space-separated list of pathspecs.
	# shellcheck disable=SC2086
	changed=$( git diff --name-only "$verified..HEAD" -- $covers | wc -l )
	# shellcheck disable=SC2086
	commits=$( git rev-list --count "$verified..HEAD" -- $covers )

	if [ "$changed" -gt 0 ]; then
		printf 'STALE  %-26s %s commit(s), %s file(s) changed\n' "$name" "$commits" "$changed"
		status=1
	else
		printf 'ok     %-26s\n' "$name"
	fi

done

if [ "$status" -ne 0 ]; then
	echo
	echo 'Re-read the stale pages against the current code, then set their verified: line to HEAD.'
	echo 'See docs/DOCUMENTATION.md.'
fi

exit "$status"
