"""Mechanical checks for the assumptions register and the approach section (v5, hero-bid).
Usage: python register_check.py <grid.md> <register.md> <approach.md>
Checks: (1) every row ID cited exists in the grid; (2) every double-quoted phrase in the register's
'why' column appears in the grid text; (3) no digits-with-units (price, hours, FTE, days) in the register;
(4) the approach section cites only existing rows and covers all of them; word count; no digits outside IDs.
"""
import re, sys

norm = lambda s: re.sub(r"\s+", " ", s.replace("“", '"').replace("”", '"').replace("’", "'")).strip()
grid = norm(open(sys.argv[1], encoding="utf-8").read())
reg = open(sys.argv[2], encoding="utf-8").read()
app = open(sys.argv[3], encoding="utf-8").read()
ids = set(re.findall(r"\bR\d+\b", " ".join(re.findall(r"(?m)^R\d+ \|", open(sys.argv[1], encoding="utf-8").read()))))
print("grid rows:", len(ids))

lines = [l for l in reg.split("\n") if re.match(r"^\|\s*[AQ]\d+\s*\|", l)]
bad_ids, quotes, miss = set(), 0, []
for l in lines:
    c = [x.strip() for x in l.strip().strip("|").split(" | ")]
    for r in re.findall(r"\bR\d+\b", c[1]):
        if r not in ids: bad_ids.add(r)
    for q in re.findall(r'"([^"]{6,})"', c[3]):
        quotes += 1
        parts = [p.strip().rstrip(".") for p in re.split(r"\.\.\.", q) if p.strip()]
        if not all(norm(p) in grid for p in parts): miss.append((c[0], q[:60]))
print(f"register lines: {len(lines)}; bad row ids: {sorted(bad_ids)}; quoted phrases: {quotes}; not found in grid: {len(miss)}")
for m in miss: print("  NOT IN GRID", m)
print("price/hour/FTE/day words in register:", re.findall(r"(?i)\$|\bFTE\b|\bhours?\b|\bdays?\b|\bprice\b|\bcost\b", reg))

body = app.split("## Grid rows not addressed")[0]
cited = set(re.findall(r"R\d+", " ".join(re.findall(r"\[(R\d+(?:, R\d+)*)\]", body))))
print("approach cites:", len(cited), "rows; unknown:", sorted(cited - ids), "; uncovered:", sorted(ids - cited))
words = len(body.split()); core = len(re.sub(r"\[[^\]]*\]", "", body).split())
print(f"approach words: {words} with brackets, {core} without")
nums = re.findall(r"\b\d+\b", re.sub(r"\[[^\]]*\]|\b[RAQB]\d+\b|\(Assumption A\d+\)", "", body))
print("bare numbers in prose:", nums)
