"""Mechanical checks for a staffing matrix.
Usage: python staffing_check.py GRID.txt ROLES.txt ANSWER.md
Checks: every grid ID once; each fact ID sits in the column of its own role and exists;
UNCOVERED is marked exactly when a row has no fact; role paragraphs exist for every role;
no digits, degree words, FTE or names-looking tokens in the role paragraphs; lists placeholders.
"""
import re, sys

grid_p, roles_p, ans_p = sys.argv[1:4]
grid = [l.split(" | ")[0] for l in open(grid_p, encoding="utf-8").read().splitlines()[1:]]
roles_t = open(roles_p, encoding="utf-8").read()
facts = {}
role_of = {}
cur = None
for l in roles_t.splitlines():
    m = re.match(r"^ROLE ([A-F])\. (.+)$", l)
    if m: cur = m.group(1); role_of[cur] = m.group(2); continue
    m = re.match(r"^\s+([A-F]\d)\. (.+)$", l)
    if m: facts[m.group(1)] = (m.group(1)[0], m.group(2))
text = open(ans_p, encoding="utf-8").read()
mat, dups = {}, []
for l in text.splitlines():
    m = re.match(r"^(R\d+) \|(.*)$", l)
    if m:
        c = [x.strip() for x in m.group(2).split("|")]
        c = (c + [""] * 7)[:7]
        if m.group(1) in mat: dups.append(m.group(1))
        mat[m.group(1)] = c
print("matrix rows:", len(mat), "grid rows:", len(grid), "duplicates:", dups, "missing:", [g for g in grid if g not in mat])
roles = list("ABCDEF")
wrong_col, unknown, unc_mismatch = [], [], []
for rid, c in mat.items():
    got = False
    for k, role in enumerate(roles):
        if c[k]:
            got = True
            for f in re.findall(r"[A-F]\d", c[k]):
                if f not in facts: unknown.append((rid, f))
                elif facts[f][0] != role: wrong_col.append((rid, role, f))
    flagged = c[6] == "UNCOVERED"
    if flagged == got: unc_mismatch.append(rid)
print("fact IDs that do not exist:", unknown)
print("fact IDs in another role's column:", wrong_col)
print("UNCOVERED flag disagrees with the cells:", unc_mismatch)
unc = [r for r, c in mat.items() if c[6] == "UNCOVERED"]
print("UNCOVERED rows (%d):" % len(unc), unc)
narr = text.split("ROLE PARAGRAPHS")[-1]
print("role paragraphs found:", re.findall(r"^Role ([A-F])", narr, re.M))
print("digits in paragraphs:", re.findall(r"\d+", narr))
print("degree/FTE/year words:", [w for w in ("phd", "ph.d", "msc", "ms ", "mph", "degree", "fte", "years of", "years'") if w in narr.lower()])
print("placeholders:", re.findall(r"\[PLACEHOLDER[^\]]*\]", narr))
