#!/usr/bin/env bash
# CHECK -- WIZARDS-TABLE roster extract (Extract lane, 2026-10-29).
# Re-parses the committed WIZARDS-TABLE.md and diffs it against the committed
# 2026-10-29-roster.{csv,md,json}. Exit code IS the verdict: 0 = PASS.
set -u
cd /root/troupe-standup || exit 1

python3 - <<'PY'
import csv, json, io, sys

SRC = "WIZARDS-TABLE.md"

with open(SRC, encoding="utf-8") as f:
    lines = f.read().splitlines()

# --- re-derive header + separator + data rows the same way as the artifact ---
header = None
for i, ln in enumerate(lines):
    cells = [c.strip() for c in ln.split("|")]
    cells = [c for c in cells if c != ""]
    if cells == ["Wizard", "Model", "Lane", "Latest check-in", "Current unit"]:
        header = i
        break

sep = None
for i in range(header + 1, header + 4):
    cells = [c.strip() for c in lines[i].split("|")]
    cells = [c for c in cells if c != ""]
    if cells and len(cells) == 5 and all(ch == "-" for ch in "".join(cells)):
        sep = i
        break

rows = []
for j in range(sep + 1, len(lines)):
    ln = lines[j].strip()
    if ln.startswith("#") or not ln:
        continue
    cells = [c.strip() for c in ln.split("|")]
    cells = [c for c in cells if c != ""]
    if all(ch == "-" for ch in "".join(cells)):
        break
    if len(cells) != 5:
        break
    rows.append(cells)

wizards = rows[:10]
assert len(wizards) == 10, f"re-derived {len(wizards)} rows, expected 10"

def rd(path):
    with open(path, encoding="utf-8") as f:
        return f.read()

fails = []

# --- 1) CSV replay ---
csv_expected = io.StringIO()
w = csv.DictWriter(csv_expected, fieldnames=["Wizard","Model","Lane","Latest check-in","Current unit"], lineterminator="\n")
w.writeheader()
for r in wizards:
    w.writerow({c: r[i] for i, c in enumerate(["Wizard","Model","Lane","Latest check-in","Current unit"])})
csv_expected = csv_expected.getvalue()

got_csv = rd("wizard-work/ledger/2026-10-29-roster.csv")
if got_csv != csv_expected:
    fails.append("CSV mismatch")

# --- 2) Markdown data-row replay ---
got_md_all = rd("wizard-work/ledger/2026-10-29-roster.md").splitlines()
data_got = []
for l in got_md_all:
    segs = [p.strip() for p in l.split("|")]
    segs = [p for p in segs if p != ""]
    if len(segs) == 5 and segs[0] == "Wizard":
        continue  # header
    if len(segs) == 5 and all(ch == "-" for ch in "".join(segs)):
        continue  # separator
    if l.startswith("| "):
        data_got.append(l)
md_rows = ["| " + " | ".join(r) + " |" for r in wizards]
if data_got != md_rows:
    fails.append("MD rows mismatch")

# --- 3) JSON replay ---
j = json.load(open("wizard-work/ledger/2026-10-29-roster.json", encoding="utf-8"))
if j.get("total_table_rows") != len(rows):
    fails.append(f"total_table_rows {j.get('total_table_rows')} != {len(rows)}")
if j.get("wizard_rows_extracted") != 10:
    fails.append("wizard_rows_extracted")
if j.get("lane_signer_rows_omitted") != len(rows) - 10:
    fails.append("lane_signer_rows_omitted")
if j.get("lane_signers") != [r[0] for r in rows[10:]]:
    fails.append("lane_signers")
if j.get("wizards") != [{"Wizard": r[0], "Model": r[1], "Lane": r[2],
                          "Latest check-in": r[3], "Current unit": r[4]} for r in wizards]:
    fails.append("wizards records")

if fails:
    print("FAIL:", "; ".join(fails))
    sys.exit(1)

print(f"PASS: roster {len(wizards)} wizard rows + {len(rows)-10} lane-signers derived from WIZARDS-TABLE.md; CSV+MD+JSON replay clean")
PY
exit $?