"""Cross-check of "Unified Field Theory" and its "UFT Verification Record": the numbers both documents print against the receipt.
Standard library, plus the pdftotext program (poppler) for X7. Reads unified_field_theory.tex/.pdf, uft_verification_record.tex/.pdf,
check_uft.py and RESULTS.txt from the current directory. The paper prints the totals and hashes; the record prints them too, with
the section table and the control table.
Counts come from the literal verdict lines of the receipt, not from its summary lines.
Prints the lines X0..X7 and a final RESULT PASS|FAIL line; if a file is missing it prints FAIL X0 and RESULT FAIL, and if the
reader stops for any other reason it prints FAIL XS with the reason and RESULT FAIL. Exits nonzero unless RESULT PASS."""
import hashlib
import os
import re
import subprocess
import sys

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(newline="\n")
OK = True
FILES = ["unified_field_theory.tex", "unified_field_theory.pdf", "uft_verification_record.tex", "uft_verification_record.pdf", "check_uft.py", "RESULTS.txt"]


def line(label, cond):
    global OK
    OK = OK and bool(cond)
    print(("PASS " if cond else "FAIL ") + label)


def finish():
    print("RESULT " + ("PASS" if OK else "FAIL"))
    sys.exit(0 if OK else 1)


def sha(p):
    return hashlib.sha256(open(p, "rb").read()).hexdigest()


# ---------------------------------------------------------------------------------------------------------------------
# One id rule for the source, inside the control table and outside it: a table cell whose text, once spaces, line breaks
# and enclosing braces are removed, is M<n>. Comments are removed before reading.
def bare_id(cell):
    c = cell.strip(" \t\n")
    while c.startswith("{") and c.endswith("}"):
        c = c[1:-1].strip(" \t\n")
    return c if re.fullmatch(r"M\d+", c) else None


def uncomment(t):
    return re.sub(r"(?<!\\)%[^\n]*\n[ \t]*", "", t)


ALIGN_ARGS = {"tabular": 1, "tabular*": 2, "tabularx": 2, "longtable": 1, "array": 1}


def skip_group(s, i, open_, close):
    """Index just past the balanced group that starts at s[i] == open_."""
    depth = 0
    while i < len(s):
        if s[i] == "\\":
            i += 2
            continue
        if s[i] == open_:
            depth += 1
        elif s[i] == close:
            depth -= 1
            if depth == 0:
                return i + 1
        i += 1
    return i


def cells(src):
    """The table cells of a TeX source: the text between cell boundaries. Boundaries are an unescaped &, a row end \\\\ (with
    its optional [..]), the start of an alignment environment with its arguments, any \\begin or \\end, table rules and a
    blank line. Matrix bodies are removed first."""
    s = uncomment(src)
    s = re.sub(r"\\begin\{(small|p|b|v|V|B)?matrix\}.*?\\end\{(small|p|b|v|V|B)?matrix\}", " ", s, flags=re.S)
    out, i, cur = [], 0, []
    while i < len(s):
        m = re.match(r"\\begin\{(tabular\*?|tabularx|longtable|array)\}", s[i:])
        if m:
            out.append("".join(cur)); cur = []
            j = i + m.end()
            n = ALIGN_ARGS[m.group(1)]
            while j < len(s) and s[j] in " \t\n":
                j += 1
            if j < len(s) and s[j] == "[":
                j = skip_group(s, j, "[", "]")
            for _ in range(n):
                while j < len(s) and s[j] in " \t\n":
                    j += 1
                if j < len(s) and s[j] == "{":
                    j = skip_group(s, j, "{", "}")
            i = j
            continue
        m = re.match(r"\\(begin|end)\{[^}]*\}|\\(toprule|midrule|bottomrule|hline)(?![A-Za-z])|\\cline\{[^}]*\}|\\cmidrule(\([^)]*\))?\{[^}]*\}", s[i:])
        if m:
            out.append("".join(cur)); cur = []
            i += m.end()
            continue
        if s.startswith("\\\\", i):
            out.append("".join(cur)); cur = []
            i += 2
            m = re.match(r"\s*\[[^\]]*\]", s[i:])
            if m:
                i += m.end()
            continue
        if s[i] == "\\" and i + 1 < len(s):
            cur.append(s[i:i + 2])
            i += 2
            continue
        if s[i] == "&":
            out.append("".join(cur)); cur = []
            i += 1
            continue
        if s.startswith("\n", i) and re.match(r"\n[ \t]*\n", s[i:]):
            out.append("".join(cur)); cur = []
            i += re.match(r"\n[ \t]*\n", s[i:]).end()
            continue
        cur.append(s[i])
        i += 1
    out.append("".join(cur))
    return out


NUM_CH = set("0123456789-+\u2212\u2013,.'\u2019\u2009\u202f\u00a0~$")


def numeral_before(t, i):
    """The whole numeral that ends just before index i (spaces between it and i are skipped): digits with any sign and
    separators, a space between two digit groups, and TeX braces and math shifts around it. Braces and $ are dropped."""
    j = i
    while j > 0 and t[j - 1] in " \t":
        j -= 1
    end = j
    while j > 0:
        c = t[j - 1]
        if c in NUM_CH or c in "{}":
            j -= 1
        elif c == " " and j >= 2 and t[j - 2].isdigit():
            j -= 1
        else:
            break
    return t[j:end].replace("{", "").replace("}", "").replace("$", "")


def numerals(t, word):
    """The numeral printed before each occurrence of word, for the occurrences that have a digit before them."""
    out = []
    for mm in re.finditer(word, t):
        tok = numeral_before(t, mm.start())
        if any(ch.isdigit() for ch in tok):
            out.append(tok)
    return out


def main():
    missing = [f for f in FILES if not os.path.isfile(f)]
    line("X0 the six files %s are present%s" % (", ".join(FILES), "" if not missing else " (missing: " + ", ".join(missing) + ")"), not missing)
    if missing:
        finish()
    tex = open("unified_field_theory.tex", encoding="utf-8").read()
    rtex = open("uft_verification_record.tex", encoding="utf-8").read()
    raw = open("RESULTS.txt", "rb").read()
    res = raw.decode("utf-8")
    rows_r = res.split("\n")
    if rows_r and rows_r[-1] == "":
        rows_r.pop()

    # X1: the receipt is well formed and its summary agrees with its literal verdicts
    kinds = ("# ", "PASS ", "FAIL ", "INFO ", "COUNT ", "RESULT ")
    passes = [r for r in rows_r if r.startswith("PASS ")]
    fails = [r for r in rows_r if r.startswith("FAIL ")]
    counts = [r for r in rows_r if r.startswith("COUNT ")]
    results = [r for r in rows_r if r.startswith("RESULT ")]
    m = re.fullmatch(r"COUNT PASS=(\d+) FAIL=(\d+)", counts[0]) if len(counts) == 1 else None
    labels = [" ".join(r.split()[1:3]) if r.split()[1] == "J" else r.split()[1] for r in passes + fails]  # "J M7" labels a control line
    line(
        "X1 the receipt has LF line ends with exactly one final LF, only verdict, section, INFO, one COUNT and one final RESULT line; its %d literal PASS and %d literal FAIL verdicts equal its COUNT, with unique labels, and RESULT PASS is the last line" % (len(passes), len(fails)),
        b"\r" not in raw
        and raw.endswith(b"\n")
        and not raw.endswith(b"\n\n")
        and all(r.startswith(kinds) for r in rows_r)
        and m is not None
        and (int(m.group(1)), int(m.group(2))) == (len(passes), len(fails))
        and not fails
        and results == ["RESULT PASS"]
        and rows_r[-1] == "RESULT PASS"
        and rows_r[-2] == counts[0]
        and len(set(labels)) == len(labels),
    )
    n_pass = len(passes)

    # X2: every total printed in the source, each numeral read whole and compared as text
    n = str(n_pass)
    cover = re.findall(r"\\textbf\{([^{}\s]+) PASS, ([^{}\s]+) FAIL\}", tex)
    prose = re.findall(r"It prints (\S+) \\texttt\{PASS\}", tex)
    total = re.findall(r"\\textbf\{total\} & \\textbf\{([^}]*)\}", rtex)
    rprose = re.findall(r"It prints (\S+) \\texttt\{PASS\}", rtex)
    r_pass = numerals(rtex, r"(?:\\texttt\{)?PASS\b")
    r_fail = numerals(rtex, r"(?:\\texttt\{)?FAIL\b")
    s_pass = numerals(tex, r"(?:\\texttt\{)?PASS\b")
    s_fail = numerals(tex, r"(?:\\texttt\{)?FAIL\b")
    s_abstr = numerals(tex, r"exact check lines")
    line(
        "X2 in the sources, every numeral printed before PASS, FAIL or exact check lines, read whole with any sign and separators: the paper's cover, prose and abstract and the record's prose and total row equal %d, and 0 before FAIL on the cover only" % n_pass,
        cover == [(n, "0")] and prose == [n] and rprose == [n] and total == [n] and s_pass == [n, n] and r_pass == [n] and s_fail == ["0"] and r_fail == [] and s_abstr == [n] and numerals(rtex, r"exact check lines") == [],
    )

    # X3: section table against literal verdicts
    sec = {}
    for r in passes:
        sec[r.split()[1][0]] = sec.get(r.split()[1][0], 0) + 1
    tabtxt = rtex[rtex.index("\\section{Receipt}"):] if "\\section{Receipt}" in rtex else ""
    tab_cells = re.findall(r"(?:^|& )([A-K]) [a-z ]+ & ([^&\\\n]*?)\s*(?=&|\\\\)", tabtxt, re.M)
    tab_pairs = [(k, v) for k, v in tab_cells if re.fullmatch(r"\d+", v)]
    tab = dict(tab_pairs)
    line("X3 the section table of the record has each section once, each count a plain numeral, and equals the literal verdicts by section: " + ", ".join("%s %s" % kv for kv in sorted(tab.items())), len(tab_cells) == len(tab_pairs) == len(tab) and {k: int(v) for k, v in tab.items()} == sec)

    # X4: hashes
    h = re.findall(r"\\hash\{([0-9a-f]{64})\}", tex)
    hr = re.findall(r"\\hash\{([0-9a-f]{64})\}", rtex)
    line("X4 the paper and the record each print the SHA-256 of check_uft.py and of RESULTS.txt first, and all four match the files", h[:2] == [sha("check_uft.py"), sha("RESULTS.txt")] and hr[:2] == h[:2] and len(h) == 2)

    # X5: control table of the record against the receipt
    tex_paper, tex = tex, rtex
    KIND_OF = {"the audit": "instance", "the register audit": "register", "the word audit": "word"}
    rec_tri = re.findall(r"^PASS J (M\d+) .*?: (the audit|the register audit|the word audit) fails \{([^}]*)\}; target (\S+) is among them$", res, re.M)
    rec = {k: set(x.strip() for x in v.split(",")) for k, _, v, _ in rec_tri}
    rec_kind = {k: KIND_OF[w] for k, w, _, _ in rec_tri}
    targets_ok = all(t in rec[k] for k, _, _, t in rec_tri)
    ctl_lines = [r for r in rows_r if re.match(r"(PASS|FAIL) J M\d+ ", r)]
    why, row_pairs = [], []
    paras = [mm.start() for mm in re.finditer(re.escape("\\paragraph{One-fault controls.}"), tex)]
    t0 = tex.find("\\begin{tabularx}", paras[0]) if len(paras) == 1 else -1
    t1 = tex.find("\\end{tabularx}", t0) if t0 >= 0 else -1
    if len(paras) != 1:
        why.append("the paragraph of the control table appears %d times" % len(paras))
    elif t0 < 0 or t1 < 0:
        why.append("the control table is missing")
    else:
        t1 += len("\\end{tabularx}")
        lines_t = tex[t0:t1].split("\n")
        HEAD = ["\\begin{tabularx}{\\textwidth}{@{}ll>{\\raggedright\\arraybackslash}X>{\\raggedright\\arraybackslash}p{0.3\\textwidth}@{}}", "\\toprule", "& Kind & Fault & Failed predicates\\\\", "\\midrule"]
        if [x.strip(" \t") for x in lines_t[:4]] != HEAD or lines_t[-1].strip(" \t") != "\\end{tabularx}" or lines_t[-2].strip(" \t") != "\\bottomrule":
            why.append("the control table does not have the prescribed heading and rules")
        bad = []
        for ln in lines_t[4:-2]:
            t = ln.strip(" \t")
            if t == "\\midrule":
                continue
            flat = re.sub(r"\\begin\{smallmatrix\}.*?\\end\{smallmatrix\}", "M", t)  # matrix cells are not columns
            cs = flat[:-2].split("&") if flat.endswith("\\\\") else []
            if len(cs) == 4 and flat.count("\\\\") == 1 and bare_id(cs[0]) and cs[1].strip(" \t") in ("instance", "register", "word"):
                row_pairs.append((bare_id(cs[0]), cs[1].strip(" \t"), cs[3].strip(" \t")))
            else:
                bad.append(t[:40])
        if bad:
            why.append("%d table lines are not exactly one row" % len(bad))
        outside = [c.strip() for c in cells(tex[:t0] + "\n\n" + tex[t1:]) if bare_id(c)]
        if outside:
            why.append("control rows outside the table (%s)" % ", ".join(bare_id(c) for c in outside))
    rows = {k: set(x.strip() for x in v.split(",")) for k, _, v in row_pairs}
    row_kind = {k: kd for k, kd, _ in row_pairs}
    diff = sorted(k for k in set(rec) | set(rows) if rec.get(k) != rows.get(k) or rec_kind.get(k) != row_kind.get(k))
    if diff:
        why.append("kinds or failed sets differ at " + ", ".join(diff))
    if len(row_pairs) != len(rows):
        why.append("a control id appears twice in the table")
    if re.findall(r"\\(input|include|InputIfFileExists)\b", tex) or re.findall(r"\\(input|include|InputIfFileExists)\b", tex_paper):
        why.append("a document reads other files")
    if not targets_ok:
        why.append("a target is not in its failed set")
    line(
        "X5 in the record, the control table and the receipt list the same %d controls, each id once on each side, each line of the table its heading, a rule or exactly one row, no cell outside it that is an id, each with the same kind and failed set, and each receipt target in its failed set%s" % (len(rec), "" if not why else " (" + "; ".join(why) + ")"),
        not why and len(rec_tri) == len(rec) == len(ctl_lines),
    )

    tex = tex_paper
    # X6: printed control counts in the sources
    nc_p = [int(x) if re.fullmatch(r"\d+", x) else -1 for x in numerals(tex, r"one-fault controls")]
    nc_r = [int(x) if re.fullmatch(r"\d+", x) else -1 for x in numerals(rtex, r"one-fault controls")]
    nc = nc_p + nc_r
    line("X6 in the sources, every count of one-fault controls (%d in the paper, %d in the record) equals %d" % (len(nc_p), len(nc_r), len(rec)), nc_p and nc_r and all(x == len(rec) for x in nc))

    # X7: the printed paper, read as layout text
    why7 = []
    try:
        pdf = subprocess.run(["pdftotext", "-layout", "uft_verification_record.pdf", "-"], capture_output=True, check=True).stdout.decode("utf-8")
        ppdf = subprocess.run(["pdftotext", "-layout", "unified_field_theory.pdf", "-"], capture_output=True, check=True).stdout.decode("utf-8")
    except (OSError, subprocess.CalledProcessError) as e:
        pdf = None
        why7.append("the PDF could not be read as text: " + type(e).__name__)
    if pdf is not None:
        plines = pdf.replace("\f", "\n").split("\n")
        # the control inventory: a printed control row is an id M<n> followed by a kind word
        hits = [mm.group(1) for mm in re.finditer(r"(?<!\S)(M\d+)\s+(instance|register|word)(?!\S)", pdf)]
        heads = [i for i, l in enumerate(plines) if re.fullmatch(r"\s*Kind\s+Fault\s+Failed predicates\s*", l)]
        prows = {}
        if len(heads) != 1:
            why7.append("the printed control table heading appears %d times" % len(heads))
        else:
            last = None
            for l in plines[heads[0] + 1:]:
                mm = re.match(r"(M\d+)\s+(instance|register|word)\s+.*?\s{2,}(\S.*?)\s*$", l)
                if mm:
                    last = mm.group(1)
                    if last in prows:
                        why7.append("%s is printed twice in the table" % last)
                    prows[last] = [mm.group(2), mm.group(3)]
                elif last and re.fullmatch(r"\s{40,}\S.*", l):
                    prows[last][1] += " " + l.strip()
                elif l.strip():
                    break
        if sorted(hits) != sorted(prows) or len(hits) != len(set(hits)):
            why7.append("the printed id-and-kind pairs anywhere in the paper are not exactly the %d rows of the table" % len(prows))
        pdiff = sorted(k for k in set(rec) | set(prows) if k not in prows or k not in rec or prows[k][0] != rec_kind[k] or set(x.strip() for x in prows[k][1].split(",")) != rec[k])
        if pdiff:
            why7.append("printed kinds or failed sets differ at " + ", ".join(pdiff))
        # the printed totals, each at its expected place
        p_cover = re.findall(r"(\S+)\s+PASS,\s+(\S+)\s+FAIL", ppdf)
        p_prose = re.findall(r"It\s+prints\s+(\S+)\s+PASS\s+lines", ppdf)
        r_prose = re.findall(r"It\s+prints\s+(\S+)\s+PASS\s+lines", pdf)
        p_total = [mm.group(1) for l in plines for mm in [re.fullmatch(r"\s*total\s+(\S+)\s*", l)] if mm]
        p_pass = numerals(ppdf, r"PASS\b")
        p_fail = numerals(ppdf, r"FAIL\b")
        p_abstr = numerals(ppdf, r"exact\s+check\s+lines")
        p_ctl = numerals(ppdf, r"one-fault\s+controls") + numerals(pdf, r"one-fault\s+controls")
        if not (p_cover == [(n, "0")] and p_prose == [n] and r_prose == [n] and p_abstr == [n] and p_total == [n] and p_pass == [n, n] and numerals(pdf, r"PASS\b") == [n] and p_fail == ["0"] and numerals(pdf, r"FAIL\b") == [] and p_ctl and all(x == str(len(rec)) for x in p_ctl)):
            why7.append("a printed total is missing, repeated or differs from the receipt")
        # the printed section table
        sec_rows = [mm for l in plines for mm in [re.fullmatch(r"\s*([A-K]) ([a-z ]+?)\s{2,}(\d+)(?:\s{2,}([A-K]) ([a-z ]+?)\s{2,}(\d+))?\s*", l)] if mm]
        p_sec = {}
        for mm in sec_rows:
            for a, b in ((1, 3), (4, 6)):
                if mm.group(a) is None:
                    continue
                if mm.group(a) in p_sec:
                    why7.append("section %s is printed twice" % mm.group(a))
                p_sec[mm.group(a)] = int(mm.group(b))
        if p_sec != sec:
            why7.append("the printed section table differs from the literal verdicts")
    line("X7 in the printed record, every id followed by a kind word is a row of the one control table, each of the %d controls is printed once with the receipt's kind and failed set, and the printed totals of both documents and the record's section table equal the receipt%s" % (len(rec), "" if not why7 else " (" + "; ".join(why7) + ")"), not why7)
    finish()


if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        raise
    except Exception as e:  # any stop before the last line is a failed check
        OK = False
        print("FAIL XS the cross-check stopped before its last line: %s: %s" % (type(e).__name__, str(e)[:120]))
        finish()
