# submission-program-readiness-review_quotecheck.py  (workflow: submission-program-readiness-review)
# Needs: Python 3 only (standard library).
# Tested with Python 3.14.3. Run with: python -I submission-program-readiness-review_quotecheck.py ...  (see the usage in the docstring below).
# Data and documents it reads are public and are NOT included: CDISC pilot files from https://github.com/cdisc-org/sdtm-adam-pilot-project,
# credited to CDISC. Code licence: MIT (see README.md in the scripts folder).
# Only this header was added; the logic is unchanged.
"""Quote check: is each backtick-quoted SAS fragment of length >= 12 in the model output really in adam_adae.sas?
Usage: python -I submission-program-readiness-review_quotecheck.py adam_adae.sas model_output.txt
Whitespace is normalised; fragments containing '...' or '..' are skipped (the model abbreviated them on purpose)."""
import re, sys
sas = open(sys.argv[1], encoding='latin1').read()
norm = lambda s: re.sub(r'\s+', ' ', s).strip().lower()
S = norm(sas)
out = open(sys.argv[2], encoding='utf-8').read()
spans = re.findall(r'`([^`\n]+)`', out)
blocks = re.findall(r'```\n(.*?)```', out, flags=re.S)
tot = ok = 0; miss = []; skipped = 0
for sp in spans:
    if len(sp) < 12: continue
    if '..' in sp: skipped += 1; continue
    tot += 1
    if norm(sp) in S: ok += 1
    else: miss.append(sp)
print(f"inline fragments checked: {tot}; found verbatim (case/space-insensitive): {ok}; skipped abbreviated: {skipped}")
for m in miss: print("NOT FOUND:", m)
for b in blocks:
    for ln in b.strip().split('\n'):
        if '...' in ln: continue
        print(("found    " if norm(ln) in S else "NOT FOUND"), ln[:90])
# cited line numbers: for 'Line N' / 'line N' / 'lines N-M' with a following code span, check span lies on those lines
L = sas.split('\n')
bad = []
for m in re.finditer(r'[Ll]ines? (\d+)(?:-(\d+))?[^`\n]{0,40}?`([^`\n]{12,})`', out):
    a = int(m.group(1)); b = int(m.group(2) or a); sp = m.group(3)
    if '..' in sp: continue
    seg = norm(' '.join(L[a-1:b]))
    if norm(sp) not in seg: bad.append((a, b, sp[:60]))
print("line-number/quote pairs not matching:", bad)
