#!/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, and the md summary totals equal the TSVs' own
# row census for the same run. This verifier recomputes the expected file set
# from the tree (git ls-tree HEAD when a .git is present, else an os.walk of
# the wizard-work directory, which in a git archive export is the same set)
# and diffs it against both tables, so a deleted row is red too.
#
# Checks, per table: 4 tab fields per line; decimal size; fn is the basename
# of rel; top is the first component of rel; no duplicate rel; every rel
# exists under the tree root; the rel set equals the tree's file set (a
# deleted row is red). Sizes are recorded, not graded: a census row for a
# file the landing commit itself touches holds the pre-commit size, so
# grading sizes would turn the verifier red on its own landing commit --
# the census grades how many files and which ones, per Q75. Across tables:
# the two TSVs are byte-identical (one generation writes both,
# gen_manifest.py, Q75). The md Totals line and its per-dir table must equal
# the recomputed counts; the summary TSV must agree with the md per-dir
# table; the csv data-row count must equal the manifest row count.
#
# Negative cells, carried in --selftest: (1) the injected beam/CHECK body
# (the seven non-row lines at lines 13-19 plus the bogus-path row, exactly as
# committed at b82b023) appended to both tables -> rc 1; (2) one row deleted
# from both tables (and the csv/md/summary adjusted to match, so only the
# tree disagrees) -> rc 1. Clean fixture -> rc 0.
#
# Usage: CHECK-wizardwork-census [tsv1] [tsv2] [md] [summary-tsv] [csv]
#   defaults: wizardwork-file-manifest.tsv wizardwork-census.tsv
#             wizardwork-census.md wizardwork-census-summary.tsv
#             wizardwork-census.csv (all beside this script)
#        CHECK-wizardwork-census --selftest
#
# Exit codes (repo tools/ contract): 0 clean, 1 graded a fault, 2 could not grade.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"

if [ "${1:-}" = "--selftest" ]; then
  python3 - "$SCRIPT_DIR" <<'PY'
import os, shutil, subprocess, sys, tempfile
from pathlib import Path

SCRIPT = Path(sys.argv[1]) / "CHECK-wizardwork-census"
# The injected block, exactly as committed at b82b023 (manifest lines 13-20).
INJECTED = (
    "beam/CHECK\n"
    "content\">\n"
    "#!/bin/bash\n"
    "# CHECK: verify all beam reliability primitives\n"
    "set -e\n"
    "cd \"$(dirname \"$(readlink -f \"$0\")\")\"\n"
    "python3 -m unittest discover -p 'test_*.py' -v\n"
    "python3 toposort/test_toposort.py\t185\ttest_toposort.py\tbeam\n"
)

def manifest_rows(files):
    # files: {rel: size}; same rule as gen_manifest.py (rel, size, fn, top).
    rows = []
    for rel in sorted(files):
        rows.append(f"{rel}\t{files[rel]}\t{Path(rel).name}\t{rel.split('/')[0]}")
    return rows

def write_fixture(base, drop_rel=None):
    ww = base / "wizard-work"
    content = {"beam/a.py": b"x=1\n", "beam/b.txt": b"hi\n", "ledger/c.md": b"# c\n"}
    for rel, data in content.items():
        p = ww / rel
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_bytes(data)
    led = ww / "ledger"
    led.mkdir(parents=True, exist_ok=True)
    shutil.copy2(SCRIPT, led / "CHECK-wizardwork-census")
    # Scan-time sizes: the five artifacts are written first as placeholders,
    # so their manifest rows hold pre-write sizes (the verifier exempts them).
    artifacts = ["wizardwork-file-manifest.tsv", "wizardwork-census.tsv",
                 "wizardwork-census.csv", "wizardwork-census.md",
                 "wizardwork-census-summary.tsv"]
    for name in artifacts:
        (led / name).write_text("placeholder\n")
    files = {}
    for top in sorted(ww.iterdir()):
        for dirpath, _dn, fns in os.walk(top):
            for fn in fns:
                p = Path(dirpath) / fn
                files[p.relative_to(ww).as_posix()] = p.stat().st_size
    if drop_rel:
        del files[drop_rel]
    rows = manifest_rows(files)
    (led / "wizardwork-file-manifest.tsv").write_text("\n".join(rows) + "\n")
    (led / "wizardwork-census.tsv").write_text("\n".join(rows) + "\n")
    per_dir = {}
    for rel in files:
        per_dir.setdefault(rel.split("/")[0], 0)
        per_dir[rel.split("/")[0]] += 1
    md = ["# wizard-work directory census", "",
          "Extract — data extraction and tables. Derived from the wizard-work",
          "tree at this commit (run 2026-11-15).", "",
          "| dir | files | scripts | data | docs | caches | other | check | checkok |",
          "|---|---|---|---|---|---|---|---|---|"]
    for top in sorted(per_dir):
        md.append(f"| {top} | {per_dir[top]} | 0 | 0 | 0 | 0 | 0 | - | no |")
    md.append("")
    md.append(f"Totals: {len(per_dir)} top-level directories, {len(files)} files "
              "(0 script, 0 data, 0 doc, 0 other, 0 cache dirs).")
    md.append("")
    (led / "wizardwork-census.md").write_text("\n".join(md))
    hdr = ["dir", "files", "scripts", "data", "docs", "caches", "other", "check", "checkok"]
    summ = ["\t".join(hdr)]
    for top in sorted(per_dir):
        summ.append("\t".join([top, str(per_dir[top]), "0", "0", "0", "0", "0", "-", "no"]))
    (led / "wizardwork-census-summary.tsv").write_text("\n".join(summ) + "\n")
    csv_rows = ["path,size_bytes,extension,kind,top_dir"]
    for rel in sorted(files):
        csv_rows.append(f"{rel},{files[rel]},.py,script,{rel.split('/')[0]}")
    (led / "wizardwork-census.csv").write_text("\n".join(csv_rows) + "\n")
    return ww

def run_fixture(ww):
    led = ww / "ledger"
    r = subprocess.run(["bash", str(led / "CHECK-wizardwork-census")],
                       cwd=str(led), capture_output=True, text=True)
    return r.returncode, r.stdout + r.stderr

tmp = Path(tempfile.mkdtemp(prefix="q75-selftest-"))
print("selftest fixtures:", tmp)
results = []

# Cell 1: clean fixture -> rc 0.
ww = write_fixture(tmp / "clean")
rc, out = run_fixture(ww)
print(f"cell clean: rc {rc}")
print(out.strip().splitlines()[-1] if out.strip() else "(no output)")
results.append(("clean", rc == 0))

# Cell 2: the injected beam/CHECK body -> rc 1, naming the fault.
ww = write_fixture(tmp / "injected")
led = ww / "ledger"
for name in ("wizardwork-file-manifest.tsv", "wizardwork-census.tsv"):
    p = led / name
    p.write_text(p.read_text() + INJECTED)
rc, out = run_fixture(ww)
ok = rc == 1 and "wrong field count" in out and "python3 toposort/test_toposort.py" in out
print(f"cell injected: rc {rc} (wrong-field-count + bogus path named: {ok})")
results.append(("injected", ok))

# Cell 3: one row deleted from both tables (csv/md/summary adjusted to
# match, so only the tree disagrees) -> rc 1, naming the deleted path.
ww = write_fixture(tmp / "deleted", drop_rel="beam/a.py")
rc, out = run_fixture(ww)
ok = rc == 1 and "beam/a.py" in out
print(f"cell deleted-row: rc {rc} (deleted path named: {ok})")
results.append(("deleted-row", ok))

bad = [name for name, ok in results if not ok]
if bad:
    print("SELFTEST FAIL:", ", ".join(bad))
    sys.exit(1)
print("SELFTEST PASS: clean 0, injected 1, deleted-row 1")
sys.exit(0)
PY
  exit 0
fi

cd "$SCRIPT_DIR"
ROOT="${WIZARDWORK_ROOT:-$(pwd)/..}"
TSV1="${1:-wizardwork-file-manifest.tsv}"
TSV2="${2:-wizardwork-census.tsv}"
MD="${3:-wizardwork-census.md}"
SUMMARY="${4:-wizardwork-census-summary.tsv}"
CSV="${5:-wizardwork-census.csv}"

python3 - "$ROOT" "$TSV1" "$TSV2" "$MD" "$SUMMARY" "$CSV" <<'PY'
import csv as csvmod
import os
import re
import subprocess
import sys
from pathlib import Path

root = Path(sys.argv[1]).resolve()
tsv1, tsv2, md, summary, csvp = (Path(a) for a in sys.argv[2:7])
tsv1, tsv2, md, summary, csvp = (Path.cwd() / p if not p.is_absolute() else p
                                  for p in (tsv1, tsv2, md, summary, csvp))
fails = []
if not root.is_dir():
    print(f"CHECK-wizardwork-census: cannot grade -- wizard-work root {root} missing")
    sys.exit(2)


def expected_tree(root):
    """rel -> size for every file under a top-level dir of wizard-work."""
    repo = root.parent
    if (repo / ".git").exists():
        try:
            out = subprocess.run(
                ["git", "-C", str(repo), "ls-tree", "-r", "-z", "-l",
                 "HEAD", "--", "wizard-work"],
                capture_output=True, check=True).stdout
            exp = {}
            for entry in out.split(b"\0"):
                if not entry:
                    continue
                meta, path = entry.decode("utf-8", "surrogateescape").split("\t", 1)
                parts = meta.split()
                if len(parts) < 4 or parts[1] != "blob":
                    continue
                if not path.startswith("wizard-work/"):
                    continue
                rel = path[len("wizard-work/"):]
                if "/" not in rel:  # loose file: gen_manifest.py skips it too
                    continue
                exp[rel] = None if parts[0] == "120000" else int(parts[3])
            return exp, "ls-tree HEAD"
        except Exception:
            pass
    exp = {}
    for top in sorted(root.iterdir()):
        if not top.is_dir():
            continue
        for dirpath, _dirnames, filenames in os.walk(top):
            for fn in filenames:
                p = Path(dirpath) / fn
                exp[p.relative_to(root).as_posix()] = p.stat().st_size
    return exp, "os.walk"


def read_tsv(path, label):
    rows = {}
    try:
        lines = path.read_text(encoding="utf-8").split("\n")
    except OSError as exc:
        fails.append(f"{label}: cannot read -- {exc}")
        return rows, 0, 0
    n4 = nbad = 0
    for ln, line in enumerate(lines, 1):
        if line == "":
            continue
        parts = line.split("\t")
        if len(parts) != 4:
            nbad += 1
            fails.append(f"{label}:{ln}: wrong field count {len(parts)}")
            continue
        n4 += 1
        rel, size, fn, top = parts
        if not re.fullmatch(r"[0-9]+", size):
            fails.append(f"{label}:{ln}: size not decimal {size!r}")
            continue
        if fn != rel.rsplit("/", 1)[-1]:
            fails.append(f"{label}:{ln}: fn {fn!r} != basename of {rel!r}")
        if top != rel.split("/", 1)[0]:
            fails.append(f"{label}:{ln}: top {top!r} != first component of {rel!r}")
        if rel in rows:
            fails.append(f"{label}:{ln}: duplicate path {rel}")
            continue
        rows[rel] = int(size)
    return rows, n4, nbad


expected, source = expected_tree(root)
tables = {}
for label, path in (("manifest", tsv1), ("census", tsv2)):
    if not path.is_file():
        print(f"CHECK-wizardwork-census: cannot grade -- {path} missing")
        sys.exit(2)
    rows, n4, nbad = read_tsv(path, path.name)
    tables[label] = rows
    print(f"{path.name}: {n4} well-formed rows, {nbad} malformed lines, "
          f"{len(rows)} distinct paths")
    for rel in rows:
        if not (root / rel).exists():
            fails.append(f"{path.name}: absent path {rel}")
    missing = sorted(set(expected) - set(rows))
    extra = sorted(set(rows) - set(expected))
    for rel in missing:
        fails.append(f"{path.name}: missing row for tree path {rel}")
    for rel in extra:
        fails.append(f"{path.name}: row for path not in tree {rel}")

# The two tables are one generation: byte-identical or stale.
try:
    same = tsv1.read_bytes() == tsv2.read_bytes()
except OSError as exc:
    fails.append(f"cannot compare tables -- {exc}")
    same = False
if not same:
    fails.append("manifest and census TSVs differ -- regenerate both in one run")

# md totals and per-dir table against the recomputed counts.
per_dir = {}
for rel in expected:
    per_dir[rel.split("/", 1)[0]] = per_dir.get(rel.split("/", 1)[0], 0) + 1
if not md.is_file():
    fails.append(f"{md.name}: missing -- the md summary is part of the census run")
else:
    text = md.read_text(encoding="utf-8")
    m = re.search(r"Totals:\s*(\d+) top-level directories,\s*(\d+) files", text)
    if not m:
        fails.append(f"{md.name}: Totals line not found")
    else:
        if int(m.group(1)) != len(per_dir):
            fails.append(f"{md.name}: Totals dirs {m.group(1)} != tree {len(per_dir)}")
        if int(m.group(2)) != len(expected):
            fails.append(f"{md.name}: Totals files {m.group(2)} != TSV rows {len(expected)}")
    md_dirs = {}
    for line in text.split("\n"):
        if line.startswith("|") and line.endswith("|"):
            cells = [c.strip() for c in line.strip("|").split("|")]
            if len(cells) >= 2 and cells[0] not in ("dir", "") \
                    and "---" not in cells[0] and cells[1].isdigit():
                md_dirs[cells[0]] = int(cells[1])
    for d, n in sorted(per_dir.items()):
        if md_dirs.get(d) != n:
            fails.append(f"{md.name}: dir {d} files {md_dirs.get(d)} != tree {n}")
    if sum(md_dirs.values()) != len(expected):
        fails.append(f"{md.name}: per-dir files sum {sum(md_dirs.values())} "
                     f"!= TSV rows {len(expected)}")

# Summary TSV must agree with the md per-dir table.
if not summary.is_file():
    fails.append(f"{summary.name}: missing -- the summary TSV is part of the census run")
else:
    try:
        slines = summary.read_text(encoding="utf-8").split("\n")
        for line in slines[1:]:
            if not line:
                continue
            parts = line.split("\t")
            if len(parts) != 9 or not parts[1].isdigit():
                fails.append(f"{summary.name}: malformed summary line {line!r}")
                continue
            if md_dirs.get(parts[0]) != int(parts[1]):
                fails.append(f"{summary.name}: dir {parts[0]} files {parts[1]} "
                             f"!= md {md_dirs.get(parts[0])}")
    except OSError as exc:
        fails.append(f"{summary.name}: cannot read -- {exc}")

# CSV data-row count must equal the manifest row count.
if not csvp.is_file():
    fails.append(f"{csvp.name}: missing -- the csv is part of the census run")
else:
    try:
        with open(csvp, newline="", encoding="utf-8") as fh:
            rows = [r for r in csvmod.reader(fh) if r]
        n_csv = len(rows) - 1 if rows and rows[0] and rows[0][0] == "path" else len(rows)
        if n_csv != len(expected):
            fails.append(f"{csvp.name}: {n_csv} data rows != TSV rows {len(expected)}")
    except OSError as exc:
        fails.append(f"{csvp.name}: cannot read -- {exc}")

print(f"CHECK-wizardwork-census: checked 2 tables + md + summary + csv "
      f"against {root} ({source}, {len(expected)} files)")
if fails:
    print("CHECK-wizardwork-census: FAIL")
    for f in fails[:25]:
        print(" ", f)
    if len(fails) > 25:
        print(f"  ... and {len(fails) - 25} more")
    sys.exit(1)
print("CHECK-wizardwork-census: OK -- every line 4 fields, every path on disk, "
      "no duplicates, sets equal the tree, md totals match")
sys.exit(0)
PY
