"""Quote check for the NIAID RFP 75N93019R00027 requirement grid (v5, hero-bid).

Source: Attachment 3 Statement of Work, PDF pages 70-82 of the SAM.gov file
(https://sam.gov/api/prod/opps/v3/opportunities/resources/files/7324d2a337e04d00a7a29ac0484dbbfe/download).
Needs: pip install pypdf (no poppler needed).

Usage: python rfp_quotecheck.py <rfp.pdf> <quotes.json> [out.json]
quotes.json: list of {"id": "R01", "pdf_page": 72, "quote": "..."}.

Two levels per quote, both on the cited PDF page only:
  EXACT        the quote is a contiguous character match of the page text (whitespace collapsed,
               curly quotes straightened, line-wrap hyphens kept: "non- <newline> computerized" is read
               as "non-computerized", which is how the PDF prints it).
  HYPHEN_ONLY  the quote matches only when hyphens are ignored (the pasted excerpt had dropped them,
               e.g. "noncomputerized" for "non-computerized").
  NO_MATCH     anything else.
Parts split by "..." or "[...]" are each matched. Word count is checked against 35.
"""
import json, re, sys
import pypdf


def norm(s):
    s = s.replace("â€™", "'").replace("â€œ", '"').replace("â€\x9d", '"').replace("â€“", "-")
    s = s.replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"')
    s = s.replace("–", "-").replace("—", "-").replace(" ", " ")
    return s


def page_text(reader, p):
    raw = norm(reader.pages[p - 1].extract_text() or "")
    raw = re.sub(r"(?m)^\s*\d+\s*\n\s*Final 22Aug19\s*$", " ", raw)
    raw = re.sub(r"-[ \t]*\n[ \t]*", "-", raw)          # line-wrap hyphen is a real hyphen here
    return re.sub(r"\s+", " ", raw).strip()


def parts(q):
    q = re.sub(r"\s+", " ", norm(q)).strip().strip('"').strip()
    q = q.rstrip(".")
    return [x.strip().rstrip(".") for x in re.split(r"\s*\[\.\.\.\]\s*|\s*\.\.\.\s*|\s*…\s*", q) if x.strip()]


def check(pdf, quotes):
    reader = pypdf.PdfReader(pdf)
    pages = {p: page_text(reader, p) for p in range(70, 83)}
    nohy = {p: t.replace("-", "") for p, t in pages.items()}
    out = []
    for q in quotes:
        ps = parts(q["quote"])
        pg = pages.get(q["pdf_page"], "")
        exact = bool(ps) and all(x in pg for x in ps)
        hy = bool(ps) and all(x.replace("-", "") in nohy.get(q["pdf_page"], "") for x in ps)
        status = "EXACT" if exact else ("HYPHEN_ONLY" if hy else "NO_MATCH")
        words = len(re.sub(r"\s*\.\.\.\s*", " ", norm(q["quote"])).split())
        out.append({"id": q["id"], "pdf_page": q["pdf_page"], "status": status, "words": words,
                    "over35": words > 35})
    return out


if __name__ == "__main__":
    quotes = json.load(open(sys.argv[2], encoding="utf-8"))
    res = check(sys.argv[1], quotes)
    n = len(res)
    c = {k: sum(1 for r in res if r["status"] == k) for k in ("EXACT", "HYPHEN_ONLY", "NO_MATCH")}
    for r in res:
        print(f'{r["id"]:>5} p.{r["pdf_page"]} {r["status"]:<12} {r["words"]} words' + ("  OVER 35" if r["over35"] else ""))
    print(f"quotes {n}: exact {c['EXACT']}, hyphen-only difference {c['HYPHEN_ONLY']}, no match {c['NO_MATCH']}, "
          f"over 35 words {sum(r['over35'] for r in res)}")
    if len(sys.argv) > 3:
        json.dump(res, open(sys.argv[3], "w", encoding="utf-8"), indent=1)
