"""Trace check for study-results-deck-from-tfls.

Usage: python -I study-results-deck-from-tfls_recompute.py [path-to-json] [good|bad]

Reads good.input_excerpt (the pasted CSR tables) and good.output (the storyline)
from study-results-deck-from-tfls.json and reports:
  1. every number in the storyline that is NOT printed anywhere in the tables;
  2. every table id cited in the storyline that is not one of the five supplied;
  3. whether each supplied table title appears in the storyline as written;
  4. interpretive phrases (for example 'clinically meaningful') that the tables
     do not contain, so they must be flagged as not in source.

What this proves: only that a number exists somewhere in the supplied tables.
It does NOT prove the number sits in the right row, column or arm, and it does
not prove the wording is sound. Those checks were done by hand (see the page).
"""
import json, re, sys, os

here = os.path.dirname(os.path.abspath(__file__))
path = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1].endswith(".json") else os.path.join(here, "study-results-deck-from-tfls.json")
which = sys.argv[-1] if sys.argv[-1] in ("good", "bad") else "good"
d = json.load(open(path, encoding="utf-8"))
excerpt = d["good"]["input_excerpt"]
text = d[which]["output"]

NUM = re.compile(r"(?<![\w.])-?\d+(?:\.\d+)?")

def norm(s):
    return s.replace("−", "-").replace("–", "-")

def strip_labels(s):
    s = norm(s)
    s = re.sub(r"Table\s+14-\d\.\d\d", " ", s)        # table ids
    s = re.sub(r"\b14-\d\.\d\d\b", " ", s)
    s = re.sub(r"\bpp?\.\s*\d+(?:-\d+)?", " ", s)      # page cites
    s = re.sub(r"\bSlide\s+\d+", " ", s, flags=re.I)
    s = re.sub(r"\b\d+\s+slides?\b", " ", s, flags=re.I)
    s = re.sub(r"ADAS[ -]?Cog\s*\(11\)", "ADAS-Cog", s)
    s = re.sub(r"\[\d\]", " ", s)                      # footnote marks
    s = re.sub(r"\bWeek\s+24\b", "Week", s)
    s = re.sub(r"\bFisher", "Fisher", s)
    return s

def nums(s):
    return [m.group(0) for m in NUM.finditer(strip_labels(s))]

src = set(nums(excerpt))
# a number written as 0.0 or 0 : keep as is; also allow '-0.0' style not needed
found = nums(text)
missing = sorted({n for n in found if n not in src}, key=lambda x: float(x))

print(f"[{which}] numbers in storyline: {len(found)} ({len(set(found))} distinct)")
print(f"distinct numbers in the supplied tables: {len(src)}")
print(f"numbers NOT printed in the tables: {len(missing)} -> {missing}")

cited = set(re.findall(r"14-\d\.\d\d", norm(text)))
supplied = set(re.findall(r"14-\d\.\d\d", norm(excerpt)))
print(f"table ids cited: {sorted(cited)}; not supplied: {sorted(cited - supplied)}")

titles = {
    "14-1.01": "Summary of Populations",
    "14-3.01": "Primary Endpoint Analysis: ADAS Cog (11) - Change from Baseline to Week 24 - LOCF",
    "14-3.02": "Primary Endpoint Analysis: CIBIC+ - Summary at Week 24 - LOCF",
    "14-5.01": "Incidence of Treatment Emergent Adverse Events",
    "14-5.02": "Treatment Emergent Serious Adverse Events",
}
flat = re.sub(r"\s+", " ", norm(text)).lower()
for tid, t in titles.items():
    ok = re.sub(r"\s+", " ", norm(t)).lower() in flat
    print(f"title {tid} verbatim in storyline: {ok}")

flags = [
    "clinically meaningful", "clinically relevant", "clinical benefit", "significant",
    "improv", "worsen", "efficacy of", "demonstrat", "well tolerated", "safe ",
    "favorable", "favourable", "no new safety", "benefit", "superior", "trend",
    "promising", "breakthrough", "proven", "effective", "causes", "caused",
    "due to the drug", "related to",
]
low = norm(text).lower()
print("interpretive phrases present (each is NOT in the source):")
hit = False
for f in flags:
    for m in re.finditer(re.escape(f), low):
        a, b = max(0, m.start() - 50), min(len(low), m.end() + 50)
        print(f"  '{f}': ...{low[a:b].replace(chr(10), ' ')}...")
        hit = True
if not hit:
    print("  none found")
