"""Collects the tests of q3_check at each even overlap (IIS-Q-0003).

usage: python3 -I work/capset/q0003/q3_target_collect.py LOG [LOG ...]
Each LOG holds the output of "q3_check one LAYER MATRIX 0 2000" for many matrices, with the
separator lines of run_target.sh.  For each even k the script prints the number of the matrices,
the number of the matrices that have a candidate, the largest count of candidates, the largest
number of the intact missing positions, the largest number of the new lost positions for each of
the four forms, the largest number of the new lost positions over all forms, the results for the
sign rules, the largest total, and how many matrices give each total.  A candidate is an antipodal
class with one position that has one to three representations.  The intact missing positions are
not in the numbers of the lost positions.  The script stops with an error if one sample does not
agree with the rules that it tests.
"""
import re
import sys


def blocks(text):
    cur = []
    for line in text.split("\n"):
        if re.fullmatch(r"matrix [0-9]{36}", line):
            if cur:
                yield cur
            cur = [line]
        elif cur:
            cur.append(line)
    if cur:
        yield cur


def one(pattern, lines):
    for ln in lines:
        m = re.fullmatch(pattern, ln)
        if m:
            g = [int(x) for x in m.groups()]
            return g[0] if len(g) == 1 else tuple(g)
    return None


table = {}
nsamp = nfail = 0
for path in sys.argv[1:]:
    with open(path, encoding="utf-8") as f:
        text = f.read()
    for b in blocks(text):
        d = one(r"direct (\d+) (\d+) (\d+) (\d+), method 2 (\d+) (\d+)", b)
        if d is None:
            continue
        nsamp += 1
        k, old, split, uns = one(r"k (\d+) intact missing (\d+) split (\d+) unsplit (\d+)", b)
        done = one(r"samples 1, direct method (\d+), disagreements between the two methods (\d+), full enumeration not done (\d+)", b)
        form = one(r"formula tested (\d+) mismatches (\d+) overlap mismatches (\d+)", b)
        trip = one(r"triples with two signs lost \(split and unsplit\) (\d+)", b)
        dd = one(r"max doubled doubleton directions for one nonantipodal pair (\d+)", b)
        ds = one(r"max doubled singleton directions for one nonantipodal pair (\d+)", b)
        cand = one(r"max intact missing positions \d+, max candidate count (\d+)", b)
        code = one(r"=== exit (\d+)", b)
        new = [d[i] - old for i in range(4)]
        ms, mu = max(d[0], d[1]), max(d[2], d[3])
        bad = []
        if code != 0:
            bad.append("exit code %s" % code)
        if done != (1, 0, 0):
            bad.append("done %s" % (done,))
        if form != (728, 0, 0):
            bad.append("formula %s" % (form,))
        if min(new) < 0 or (d[4], d[5]) != (ms - old, mu - old) or (split, uns) != (ms, mu):
            bad.append("methods direct %s method 2 %s old %d split %d unsplit %d" % (d[:4], d[4:], old, split, uns))
        if trip != 0 or dd > 1 or ds > 2:
            bad.append("sign rules triples %s doubletons %s singletons %s" % (trip, dd, ds))
        if max(d) > 15:
            bad.append("more than 15 positions")
        if bad:
            nfail += 1
            print("RULE NOT SATISFIED: k %d matrix %s : %s" % (k, b[0][7:], " ; ".join(bad)))
        row = table.setdefault(k, {"n": 0, "withcand": 0, "cand": 0, "old": 0, "form": [0] * 4, "new": 0,
                                   "dd": 0, "ds": 0, "total": 0, "dist": {}})
        row["n"] += 1
        row["withcand"] += cand > 0
        row["cand"] = max(row["cand"], cand)
        row["old"] = max(row["old"], old)
        for i in range(4):
            row["form"][i] = max(row["form"][i], new[i])
        row["new"] = max(row["new"], max(new))
        row["dd"] = max(row["dd"], dd)
        row["ds"] = max(row["ds"], ds)
        row["total"] = max(row["total"], max(split, uns))
        key = max(split, uns)
        row["dist"][key] = row["dist"].get(key, 0) + 1
print("k : matrices : with a candidate : most candidates : most intact missing : new lost (2,1) : new lost (1,2) : new lost (3,0) : new lost (0,3) : most new lost : most doubled doubleton directions : most doubled singleton directions : most positions")
for k in sorted(table):
    r = table[k]
    print("%d : %d : %d : %d : %d : %s : %d : %d : %d : %d : %s" % (
        k, r["n"], r["withcand"], r["cand"], r["old"], " : ".join(str(x) for x in r["form"]),
        r["new"], r["dd"], r["ds"], r["total"],
        " ".join("%d:%d" % kv for kv in sorted(r["dist"].items()))))
tot = sum(r["n"] for r in table.values())
print("matrices %d, matrices that do not satisfy a rule %d" % (tot, nfail))
if tot == 0 or nfail or tot != nsamp:
    sys.exit(1)
