#!/usr/bin/env bash
# CHECK — check-in census extract (Extract lane, 2026-10-27).
# Exits 0 iff the committed TSV re-derives field-for-field from the raw
# checkins/*.md files. The re-derivation is a separate implementation that
# reads the disk listing, so it cannot reuse the extraction script's Counter
# logic; it also self-asserts the two headline figures (96 files, 33 dates).
set -u

cd "$(dirname "${BASH_SOURCE[0]}")" || exit 1
ROOT=/root/troupe-standup
SRC=$ROOT/checkins
TSV=2026-10-27-checkin-census.tsv

[ -f "$TSV" ] || { echo "FAIL: $TSV missing"; exit 1; }

python3 - "$SRC" "$TSV" <<'PY'
import collections
import os
import re
import sys

src, tsv = sys.argv[1], sys.argv[2]

per_date = collections.Counter()
per_wizard = collections.Counter()
for fn in os.listdir(src):
    if not fn.endswith('.md'):
        continue
    name = fn[:-3]
    if not re.match(r'^\d{4}-\d{2}-\d{2}-', name):
        continue
    date = name[:10]
    rest = name[11:]
    wizard = re.sub(r'-\d+$', '', rest)
    per_date[date] += 1
    per_wizard[wizard] += 1

# Independent re-derivation of the per-wizard table (same canonical sort:
# count desc, name asc).
expected = []
for w in sorted(per_wizard, key=lambda w: (-per_wizard[w], w)):
    expected.append((w, str(per_wizard[w])))

with open(tsv, encoding='utf-8') as f:
    header = f.readline().rstrip('\n')
    actual = []
    for line in f:
        line = line.rstrip('\n')
        if line:
            actual.append(tuple(line.split('\t')))

if header != 'wizard\tcheckin_files':
    print('FAIL: unexpected header: %r' % header)
    sys.exit(1)

if expected != actual:
    print('FAIL: re-derived table != committed TSV')
    print('expected:')
    for r in expected:
        print('\t'.join(r))
    print('actual:')
    for r in actual:
        print('\t'.join(r))
    sys.exit(1)

if sum(per_date.values()) != 96:
    print('FAIL: expected 96 date-prefixed files, got %d' % sum(per_date.values()))
    sys.exit(1)
if len(per_date) != 33:
    print('FAIL: expected 33 distinct dates, got %d' % len(per_date))
    sys.exit(1)

print('OK: checkin-census.tsv verified (%d rows, %d files, %d dates)' % (len(actual), sum(per_date.values()), len(per_date)))
PY
