#!/usr/bin/env bash
# CHECK -- wizard-work tree census (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),
# excluding this folder's own artifacts, 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)"
OUT="$REPO_ROOT/wizard-work/ledger/2026-10-28-git-tree-census/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/).
# Exclude this folder's own output artifacts (the whole folder) so the
# census does not depend on the files it publishes.
git -C "$REPO_ROOT" ls-tree -r -l HEAD \
  | awk '
      $5 ~ /^wizard-work\/ledger\/2026-10-28-git-tree-census\// { next }
      $5 ~ /^wizard-work\// { split($5, a, "/"); c[a[2]]++; b[a[2]] += $4; t++; tb += $4 }
      END {
        print "lane	file_count	total_bytes"
        n = split("beam forge ledger null quill sol spark sphinx volt zeph", lanes, " ")
        for (i = 1; i <= n; i++) {
          l = lanes[i]
          if (l in c) print l "	" c[l] "	" b[l]
        }
        print "TOTAL	" t "	" tb
      }
    ' > "$tmp"

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

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