#!/bin/bash
# CHECK-wizardwork-census -- verify the wizard-work census TSVs round-trip from the tree.
#
# Q75 (ledger lane): both TSVs must regenerate from the tree through committed code
# and round-trip -- every line has the declared field count, every path exists on
# disk, no duplicates. This verifier is red on a line whose path is absent from disk
# and on a line with the wrong field count (the two negative cells: the injected
# beam/CHECK body, and a deleted row), and green once both tables are clean.
#
# Usage: CHECK-wizardwork-census [tsv1] [tsv2]
#   defaults: wizardwork-file-manifest.tsv wizardwork-census.tsv (in this directory)
#
# Exit codes (repo tools/ contract): 0 clean, 1 graded a fault, 2 could not grade.
set -euo pipefail
cd "$(dirname "$(readlink -f "$0")")"

ROOT="$(pwd)/.."            # wizard-work dir, parent of ledger/
TSV1="${1:-wizardwork-file-manifest.tsv}"
TSV2="${2:-wizardwork-census.tsv}"

python3 - "$ROOT" "$TSV1" "$TSV2" <<'PY'
import os, sys
from pathlib import Path
root = Path(sys.argv[1]).resolve()
if not root.is_dir():
    print(f'CHECK-wizardwork-census: cannot grade -- wizard-work root {root} missing')
    sys.exit(2)
fails = []
tables = 0
for tsv in sys.argv[2:]:
    p = Path(tsv)
    if not p.is_absolute():
        p = Path.cwd() / p
    if not p.is_file():
        print(f'CHECK-wizardwork-census: cannot grade -- {p} missing')
        sys.exit(2)
    tables += 1
    seen = set()
    n4 = nbad = 0
    with open(p) as f:
        for ln, line in enumerate(f, 1):
            line = line.rstrip('\n')
            if not line:
                continue
            parts = line.split('\t')
            if len(parts) != 4:
                nbad += 1
                fails.append(f'{p.name}:{ln}: wrong field count {len(parts)}')
                continue
            n4 += 1
            rel, size, fn, top = parts
            if rel in seen:
                fails.append(f'{p.name}:{ln}: duplicate path {rel}')
            seen.add(rel)
            if not (root / rel).exists():
                fails.append(f'{p.name}:{ln}: absent path {rel}')
    print(f'{p.name}: {n4} well-formed rows, {nbad} malformed lines, {len(seen)} distinct paths')
print(f'CHECK-wizardwork-census: checked {tables} tables against {root}')
if fails:
    print('CHECK-wizardwork-census: FAIL')
    for f in fails[:25]:
        print(' ', f)
    sys.exit(1)
print('CHECK-wizardwork-census: OK -- every line 4 fields, every path on disk, no duplicates')
sys.exit(0)
PY
