"""Independent verifier (Python, own code): recompute the 96 cells from adam_adsl.xpt and compare to the
answer key parsed from input_paste.txt (the key typed from the CSR). Writes verifier_cells.csv."""
import sys, re, csv
from decimal import Decimal, ROUND_HALF_UP
import pandas as pd

src, keyf, out = sys.argv[1:4]
a = pd.read_sas(src, format="xport", encoding="latin1")
a = a[a.ITTFL == "Y"]
cols = ["Placebo", "Xanomeline Low Dose", "Xanomeline High Dose", "Total"]
grp = {c: a[a.TRT01P == c] for c in cols[:3]}; grp["Total"] = a
hisp = a.ETHNIC == "HISPANIC OR LATINO"
a = a.assign(R=a.RACE.map({"WHITE": "Caucasian", "BLACK OR AFRICAN AMERICAN": "African Descent"}).fillna("Other"))
a.loc[hisp, "R"] = "Hispanic"
grp = {c: a[a.TRT01P == c] for c in cols[:3]}; grp["Total"] = a

def hu(x, nd):
    return str(Decimal(repr(float(x))).quantize(Decimal(1).scaleb(-nd), rounding=ROUND_HALF_UP))
def pc(n, N):
    p = Decimal(n) * 100 / Decimal(N)
    if 0 < p < Decimal("0.5"): return f"{n} (<1%)"
    return f"{n} ({p.quantize(Decimal(1), rounding=ROUND_HALF_UP)}%)"
res = {}
for blk, var, nds in [("Age (y)", "AGE", (1, 2, 1)), ("Baseline weight (kg)", "WEIGHTBL", (1, 2, 1))]:
    for c, g in grp.items():
        x = g[var].dropna()
        for st, v in [("n", str(len(x))), ("Mean", hu(x.mean(), nds[0])), ("SD", hu(x.std(), nds[1])),
                      ("Median", hu(x.median(), nds[2])), ("Min", hu(x.min(), nds[2])), ("Max", hu(x.max(), nds[2]))]:
            res[(blk, st, c)] = v
for blk, var, levs in [("Age group", "AGEGR1", ["<65", "65-80", ">80"]), ("Sex", "SEX", ["M", "F"]),
                       ("Race", "R", ["Caucasian", "African Descent", "Hispanic", "Other"]),
                       ("Baseline BMI group", "BMIBLGR1", ["<25", "25-<30", ">=30"])]:
    for l in levs:
        for c, g in grp.items():
            res[(blk, l, c)] = pc(int((g[var] == l).sum()), len(g))

# parse key
key = {}; blk = None
names = {"Age (y)": "Age (y)", "Age group": "Age group", "Sex": "Sex", "Race (Origin)": "Race",
         "Baseline weight (kg)": "Baseline weight (kg)", "Baseline BMI group": "Baseline BMI group"}
lab = {"<65 yrs": "<65", "65-80 yrs": "65-80", ">80 yrs": ">80", "Male": "M", "Female": "F"}
txt = open(keyf, encoding="utf8").read().split("CSR Table 14-2.01")[1].splitlines()[2:]
for ln in txt:
    if not ln.strip(): continue
    if not ln.startswith(" "):
        blk = names[ln.strip()]; continue
    m = re.match(r"\s+(\S+(?: \S+)*?)\s{2,}(.+)$", ln)
    st, rest = m.group(1), [s.strip() for s in m.group(2).split("|")]
    rest = ["0 (0%)" if s == "0" else s for s in rest]
    key[(blk, lab.get(st, st))] = rest
bad = 0; rows = []
for (b, st), vals in key.items():
    for c, kv in zip(cols, vals):
        rv = res[(b, st, c)]
        ok = rv.replace(" ", "") == kv.replace(" ", "")
        bad += not ok
        rows.append([b, st, c, rv, kv, "MATCH" if ok else "MISMATCH"])
w = csv.writer(open(out, "w", newline="", encoding="utf8"))
w.writerow(["block", "stat", "column", "recomputed", "csr", "result"]); w.writerows(rows)
print(len(rows), "cells;", len(rows) - bad, "match;", bad, "mismatch")
