#!/usr/bin/env bash
# CHECK — verifier for the check-in census artifact (Extract lane: data extraction).
#
# Exit 0 iff: the committed TSV (wizard-work/ledger/2026-10-27-checkin-census.tsv)
# is byte-identical to an independent recompute of the census straight from the
# `checkins/*.md` source directory.
#
# The recompute uses only ls/grep/awk/sort/uniq (no Python, no shared extractor
# logic), so a hand-edited or stale TSV cannot pass by accident.
#
# Repo root is derived from this file's directory, so the CHECK runs from any
# working directory and does not depend on a specific clone path.

set -u

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

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

# Independent recompute: header plus date prefix of each check-in file's basename.
expected=$(echo "date,checkin_files"; ls "$SRC"/*.md 2>/dev/null \
  | grep -v 'README\.md$' \
  | awk -F/ '{n=split($0, a, "/"); name=a[n]; sub(/\.md$/, "", name); print substr(name, 1, 10)}' \
  | sort \
  | uniq -c \
  | awk '{print $2 "," $1}')

diff -u "$OUT" - <<<"$expected" >/dev/null \
  || { echo "FAIL: census mismatch against independent recompute" >&2; exit 1; }

echo "PASS: census rows=$(tail -n +2 "$OUT" | grep -c .); recomputed from $SRC"
