#!/usr/bin/env python3
"""Compares the tables in the logs of verify_q0002.py and verify_q0002.c: python3 compare_q0002.py PYTHON_LOG C_LOG."""
import re
import sys

NUMBER_PAIR = re.compile(r"^(\d+):(\d+)$")
NAMES = ("TAU", "DIST", "JMIN", "UNLOCK", "JOINT", "JOINTALL")


def tables(path):
    """Read the tables of one log; return (dict of the tables, True if the log has ALL CHECKS PASSED)."""
    out = {name: {} for name in NAMES}
    passed = False
    for line in open(path, encoding="utf-8"):
        f = line.split()
        passed = passed or line.rstrip("\n") == "ALL CHECKS PASSED"
        if not f or f[0] not in out:
            continue
        try:
            if f[0] == "TAU":
                out["TAU"][int(f[1])] = tuple(int(x) for x in f[2:6])
            elif f[0] == "DIST":
                out["DIST"][(int(f[1]), int(f[2]))] = int(f[3])
            elif f[0] == "JMIN":
                out["JMIN"][int(f[1].split("=")[1])] = tuple(int(x) for x in f[2:5])
            elif f[0] == "UNLOCK":
                out["UNLOCK"][int(f[1])] = (int(f[2]), int(f[3]))
            elif "=" in f[1]:
                k = int(f[1].split("=")[1])
                for tok in f[2:]:
                    m = NUMBER_PAIR.match(tok)
                    if m:
                        out[f[0]][(k, int(m.group(1)))] = int(m.group(2))
        except ValueError:
            continue
    return out, passed


def main():
    if len(sys.argv) != 3:
        print(__doc__)
        return 2
    a, pa = tables(sys.argv[1])
    b, pb = tables(sys.argv[2])
    ok = True
    for name in NAMES:
        same = a[name] == b[name] and len(a[name]) > 0
        print("%s: table %s of the Python log = table %s of the C log (%d entries)"
              % ("PASS" if same else "FAIL", name, name, len(a[name])))
        ok = ok and same
    print("%s: both logs contain the line ALL CHECKS PASSED" % ("PASS" if pa and pb else "FAIL"))
    if ok and pa and pb:
        print("\nTHE TWO VERIFIERS AGREE")
        return 0
    return 1


if __name__ == "__main__":
    sys.exit(main())
