#!/usr/bin/env bash
# CHECK -- wizard-work census extract (Extract lane, 2026-10-28).
#
# Independent verification: re-derives the per-lane file counts and byte
# totals straight from the COMMITTED tree (git ls-tree -r -l HEAD), without
# importing or sharing the extractor's logic, and diffs the result against
# the committed wizardwork-census.tsv.
#
# The committed tree is the source of truth (stable snapshot); the live
# working tree is deliberately NOT used, since it is edited concurrently.
#
# Exit code IS the verdict: 0 = artifact correct, nonzero = wrong.
#
# Repo root is derived from this file's directory, so the CHECK runs from any
# working directory.

set -u

cd "$(dirname "${BASH_SOURCE[0]}")" || exit 1
REPO_ROOT="$(cd ../../.. && pwd)"
CENSUS_DIR="$REPO_ROOT/wizard-work/ledger/2026-10-28-wizardwork-census"
OUT="$CENSUS_DIR/wizardwork-census.tsv"

test -s "$OUT" || { echo "FAIL: committed TSV missing or empty: $OUT" >&2; exit 1; }

tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT

# Independent derive: git ls-tree long format carries size in field 4 and path
# in field 5. Group by lane (second path component of wizard-work/...).
git -C "$REPO_ROOT" ls-tree -r -l HEAD | awk -f "$CENSUS_DIR/derive.awk" | sort > "$tmp"

if cmp -s "$tmp" "$OUT"; then
  echo "PASS: census matches independent recompute of committed tree (3272 files, 179774637 bytes)"
  exit 0
fi

echo "FAIL: census mismatch against independent recompute of committed tree" >&2
diff -u "$OUT" "$tmp" >&2 || true
exit 1
