# rfp-biostat-scope-extraction_quotecheck.py  (workflow: rfp-biostat-scope-extraction)
# Needs: Python 3, poppler pdftotext on PATH. No third-party Python packages.
# Tested with Python 3.14.3. Run with: python -I rfp-biostat-scope-extraction_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-match and requirement-sentence completeness check for rfp-biostat-scope-extraction.

Source: NIAID RFP 75N93019R00027, Attachment 3 Statement of Work, PDF pages 70-82
(https://sam.gov/api/prod/opps/v3/opportunities/resources/files/7324d2a337e04d00a7a29ac0484dbbfe/download).
Needs poppler's pdftotext on PATH.

Usage: python rfp-biostat-scope-extraction_quotecheck.py <rfp.pdf> <grid_quotes.json> [excerpt.txt]
grid_quotes.json: list of {"id": "...", "pdf_page": 76, "quote": "..."}.

Prints (1) exact-text-match result for each quote (whitespace-normalised, same PDF page),
(2) the count of requirement sentences (shall / must / will provide) in the whole SOW and in the
excerpt pages used, and which of them contain at least one grid quote.
"""
import json, re, subprocess, sys

pdf, quotes_path = sys.argv[1], sys.argv[2]
quotes = json.load(open(quotes_path, encoding="utf-8"))

def norm(s):
    s = s.replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"')
    s = re.sub(r"\d+ Final 22Aug19", " ", s)
    return re.sub(r"\s+", " ", s).strip()

pages = {}
for p in range(70, 83):
    t = subprocess.run(["pdftotext", "-f", str(p), "-l", str(p), pdf, "-"],
                       capture_output=True).stdout.decode("utf-8", "replace")
    pages[p] = norm(t)
whole = norm(" ".join(pages[p] for p in sorted(pages)))

# (1) exact quote match
bad = 0
print("== Quote match ==")
for q in quotes:
    qt = norm(q["quote"]).rstrip(".")
    qt_parts = [x.strip() for x in re.split(r"\s*\.\.\.\s*|\s*\[\.\.\.\]\s*", qt) if x.strip()]
    in_page = all(x in pages.get(q["pdf_page"], "") for x in qt_parts)
    in_doc = all(x in whole for x in qt_parts)
    status = "EXACT, cited page" if in_page else ("EXACT, other page" if in_doc else "NO MATCH")
    if status != "EXACT, cited page":
        bad += 1
    print(f'{q["id"]:>5}  p.{q["pdf_page"]}  {status}  ({len(qt.split())} words)')
print(f"quotes: {len(quotes)}, not exact on cited page: {bad}")

# (2) requirement sentences
def sentences(text):
    return [s for s in re.split(r"(?<=[.;])\s+(?=[A-Z0-9a-z(])", text) if s]

pat = re.compile(r"\b(shall|must|will provide)\b")
def req(text):
    return [s for s in sentences(text) if pat.search(s)]

all_req = req(whole)
print("\n== Requirement sentences (shall / must / will provide) ==")
print("whole SOW (PDF 70-82):", len(all_req))
qn = [norm(q["quote"]).rstrip(".") for q in quotes]
def report(label, txt):
    r = req(txt)
    print(label, ":", len(r))
    for s in r:
        hit = [q["id"] for q, n in zip(quotes, qn) if n and (n in s or s in n)]
        print(" ", "COVERED" if hit else "NOT COVERED", hit, "|", s[:110])
if len(sys.argv) > 3:   # optional: the excerpt text file given to the model
    report("excerpt as given to the model", norm(open(sys.argv[3], encoding="utf-8").read()))
