"""Recompute and trace checks for adrg-section-drafts (CDISCPILOT01).
Usage: python -I adrg-section-drafts_recompute.py <source_dir> <csr_pdf_text.txt>
  source_dir = content/examples/cdiscpilot01-alzheimers/source (adam_define.xml, adam_adsl.xpt unmodified)
  csr_pdf_text.txt = pdftotext -layout output of cdiscpilot01_csr.pdf pages 1-8 (any text containing the synopsis)
Checks: (1) dataset table in the draft vs adam_define.xml; (2) every number in the draft vs adam_adsl.xpt and the CSR text;
(3) the quoted CSR sentences occur verbatim in the CSR text. Read-only; nothing is written."""
import re, sys
import pandas as pd

src, csr_txt = sys.argv[1], sys.argv[2]
xml = open(src + "/adam_define.xml", encoding="cp1252").read()
csr = re.sub(r"\s+", " ", open(csr_txt, encoding="utf-8", errors="replace").read())

# (1) dataset table from define.xml
groups = re.findall(r"<ItemGroupDef .*?</ItemGroupDef>", xml, re.S)
def attr(g, a):
    m = re.search(a + r'="([^"]*)"', g)
    return re.sub(r"\s+", " ", m.group(1)).strip() if m else None
rows = {}
for g in groups:
    rows[attr(g, "Name")] = dict(label=attr(g, "def:Label"), cls=attr(g, "def:Class"),
                                 structure=attr(g, "def:Structure"), comment=attr(g, "Comment"))
print("ItemGroupDef count in adam_define.xml:", len(rows))
draft = {  # as written in the draft's section 5 table (labels and structures; 'same as' rows resolved)
 "ADSL": ("Subject-Level Analysis", "ADSL", "one record per subject"),
 "ADAE": ("Adverse Events Analysis Dataset", "ADAE", "one record per subject per adverse event"),
 "ADLBC": ("Analysis Dataset Lab Blood Chemistry", "BDS", "one record per subject per parameter per analysis visit"),
 "ADLBH": ("Analysis Dataset Lab Hematology", "BDS", "SAME:ADLBC"),
 "ADLBHY": ("Analysis Dataset Lab Hy's Law", "BDS", "SAME:ADLBC"),
 "ADQSADAS": ("ADAS-Cog Analysis", "BDS", "one record per subject per parameter per analysis visit per analysis date"),
 "ADQSCIBC": ("CIBIC+ Analysis", "BDS", "SAME:ADQSADAS"),
 "ADQSNPIX": ("NPI-X Item Analysis Data", "BDS", "SAME:ADQSADAS"),
 "ADTTE": ("AE Time To 1st Derm. Event Analysis", "BDS", "one record per subject per parameter"),
 "ADVS": ("Vital Signs Analysis Dataset", "BDS", "one record per subject per parameter per analysis visit per analysis timepoint"),
}
bad = 0
for n, (lab, cls, st) in draft.items():
    r = rows.get(n)
    st_real = rows[st[5:]]["structure"] if st.startswith("SAME:") else st
    ok = r and r["label"] == lab and r["cls"] == cls and r["structure"] == st_real
    if st.startswith("SAME:"):
        ok = ok and rows[n]["structure"] == rows[st[5:]]["structure"]
    print(f"  {n:9s} label/class/structure match define.xml: {bool(ok)}")
    bad += (not ok)
print("dataset rows mismatching:", bad, "| ADAE Comment:", rows["ADAE"]["comment"])
print("other datasets with a Comment other than blank:", [n for n, r in rows.items() if n != "ADAE" and r["comment"].strip()])
print("StandardName/Version/DefineVersion:", re.findall(r'def:(?:StandardName|StandardVersion|DefineVersion)="([^"]*)"', xml))

# population flag comments as pasted in the excerpt
exp = {"ITTFL": "Y if ARMCD ne ' '. N otherwise",
       "SAFFL": "Y if ITTFL='Y' and TRTSDT ne missing. N otherwise",
       "COMP24FL": "Y if subject has a SV.VISITNUM=12 and ENDDT>= date of visit 12 , N otherwise"}
for v, text in exp.items():
    m = re.search(r'<ItemDef OID="ADSL\.%s".*?Comment="([^"]*)"' % v, xml, re.S)
    c = m.group(1).replace("&apos;", "'").replace("&gt;", ">").replace("&lt;", "<")
    print(f"  {v} comment matches excerpt:", re.sub(r"\s+", " ", c) == text)
m = re.search(r'<ItemDef OID="ADSL\.EFFFL".*?Comment="([^"]*)"', xml, re.S)
print("  EFFFL comment (typo: unclosed quote after SAFFL='Y):", m.group(1).replace("&apos;", "'").replace("&gt;", ">"))

# (2) numbers from ADSL
adsl = pd.read_sas(src + "/adam_adsl.xpt", format="xport", encoding="latin1")
print("ADSL records:", len(adsl), "| distinct USUBJID:", adsl.USUBJID.nunique(), "| distinct SITEID:", adsl.SITEID.nunique())
for f in ["ITTFL", "SAFFL", "EFFFL", "COMP24FL"]:
    print(f, adsl[f].value_counts(dropna=False).to_dict())
itt = adsl[adsl.ITTFL == "Y"]
print("ITTFL=Y by TRT01P:", itt.TRT01P.value_counts().to_dict(), "total", len(itt))
print("All ADSL records by ARM:", adsl.ARM.value_counts(dropna=False).to_dict())

# (3) verbatim CSR quotes and the synopsis facts used in the draft
quotes = [
 "Safety and Efficacy of the Xanomeline Transdermal Therapeutic System (TTS) in Patients with Mild to Moderate Alzheimer's Disease",
 "prospective, randomized, multi-center, double-blind, placebo-controlled, parallel-group study",
 "Subjects were randomized equally to placebo, xanomeline low dose, or xanomeline high dose. Subjects applied 2 patches daily and were followed for a total of 26 weeks.",
 "254 subjects were randomized (86 placebo, 84 xanomeline low dose, 84 xanomeline high dose)",
 "06 July 2012 to 05 March 2015", "Phase 2", "conducted at 17 centers",
 "used the efficacy population with LOCF imputation for any missing values at Week 24",
 "summarized by system organ class (SOC) and preferred term (PT)",
 "compared across the treatment groups using Kaplan-Meier methods",
]
for q in quotes:
    print("  CSR quote found:", re.sub(r"\s+", " ", q).lower() in csr.lower(), "|", q[:60])
