"""Mechanical checks for a bid fit screen.
Usage: python fit_screen_check.py GRID.txt FACTS.txt ANSWER.md
GRID.txt: lines 'ID | section | page | plain words | exact quote | type | deadline'
FACTS.txt: lines 'B1. text'
ANSWER.md: 'ID | status | fact IDs | reason' rows, then a five-row risk list.
Checks: every grid ID once; status in Covered/Partly/Gap; cited fact IDs exist; Covered/Partly cite a fact;
Gap rows that still cite a fact are listed; every double-quoted phrase in a reason sits in that grid row;
counts add up; risk list rows exist; no price, hours or date words.
"""
import re, sys

grid_p, facts_p, ans_p = sys.argv[1:4]
norm = lambda s: re.sub(r"\s+", " ", s.replace("’", "'")).lower().strip(" .,;")
grid = {}
for l in open(grid_p, encoding="utf-8").read().splitlines()[1:]:
    c = [x.strip() for x in l.split(" | ")]
    grid[c[0]] = norm(" ".join(c[1:5]))
facts = set(re.findall(r"^(B\d+)\.", open(facts_p, encoding="utf-8").read(), re.M))
text = open(ans_p, encoding="utf-8").read()
rows = {}
dups = []
for l in text.splitlines():
    m = re.match(r"^(R\d+) \| (Covered|Partly|Gap) \| (.+?) \| (.+)$", l)
    if m:
        if m.group(1) in rows: dups.append(m.group(1))
        rows[m.group(1)] = m.groups()[1:]
print("rows parsed:", len(rows), "grid rows:", len(grid), "duplicates:", dups)
print("missing from answer:", [i for i in grid if i not in rows], "unknown IDs:", [i for i in rows if i not in grid])
bad_f, gap_with_fact, no_fact, qbad = [], [], [], []
for i, (st, fid, reason) in rows.items():
    cited = re.findall(r"B\d+", fid)
    bad_f += [(i, f) for f in cited if f not in facts]
    if st in ("Covered", "Partly") and not cited: no_fact.append(i)
    if st == "Gap" and cited: gap_with_fact.append(i)
    for q in re.findall(r'"([^"]+)"', reason):
        for part in re.split(r"\.\.\.|…", q):
            p = norm(part)
            if len(p) > 2 and p not in grid.get(i, ""): qbad.append((i, part.strip()))
print("cited fact IDs that do not exist:", bad_f)
print("Covered/Partly rows with no fact:", no_fact)
print("Gap rows that still cite a fact (listed so a reader can see why):", gap_with_fact)
print("quoted phrases not found in that grid row:", qbad)
from collections import Counter
print("counts:", dict(Counter(v[0] for v in rows.values())), "total", len(rows))
tail = text.split("highest delivery risk")[-1]
top = re.findall(r"^\d\. (R\d+)\.", tail, re.M)
print("risk list rows:", top, "all exist:", all(t in grid for t in top))
low = text.lower()
print("price/hours/date/FTE words:", [w for w in ("price", "pricing", "cost", "hours", "fte", "$", "bid or no-bid", "no-bid") if w in low])
