"""Collects the logs of phase 2 of run_all.sh (IIS-Q-0003): the local search and the random matrices.

usage: python3 -I work/capset/q0003/q3_search_collect.py LOG [LOG ...]
Each LOG holds the output of the mode climb or pairs of q3_check.  The script prints one line for
each log, then one line for each overlap k.  "samples" are the relative positions that the
program counted.  "split" and "unsplit" are the largest numbers of missing sums in the two
puncture forms.  A missing sum is a position of the third layer that no pair (a, s) gives with a
in A without U and s in S without V.  The intact missing positions (no representation before the
punctures) are in these numbers.  The script stops with an error if a log shows a disagreement
between the two methods of the program, a mismatch of the spectral identity, a triple that loses
both signs, or more than 15 positions.
"""
import re
import sys

RE_K = re.compile(r"k (\d+) samples (\d+) max split (\d+) max unsplit (\d+)$")
RE_DONE = re.compile(r"samples (\d+), direct method (\d+), disagreements between the two methods (\d+), full enumeration not done (\d+)$")
RE_FORM = re.compile(r"formula tested (\d+) mismatches (\d+) overlap mismatches (\d+)$")
RE_TRIP = re.compile(r"triples with two signs lost \(split and unsplit\) (\d+)$")
RE_DD = re.compile(r"max doubled doubleton directions for one nonantipodal pair (\d+)$")
RE_DS = re.compile(r"max doubled singleton directions for one nonantipodal pair (\d+)$")
RE_OLD = re.compile(r"max intact missing positions (\d+), max candidate count (\d+)$")
RE_EXIT = re.compile(r"exit (\d+)$")
RE_HUNT = re.compile(r"samples with fewer candidates than the limit: (\d+)$")

print("log : samples : not counted by both methods : formula tested : mismatches : overlap mismatches : "
      "triples with two signs lost : most doubled doubleton directions : most doubled singleton directions : "
      "most intact missing : most candidates : most positions : exit : hunt samples below the limit")
tot_samples = 0
bad = 0
table = {}
for path in sys.argv[1:]:
    done = form = trip = dd = ds = old = code = hunt = None
    per_k = {}
    with open(path, encoding="utf-8") as f:
        for ln in f:
            ln = ln.rstrip("\n")
            m = RE_DONE.fullmatch(ln)
            if m:
                done = tuple(int(x) for x in m.groups())
                continue
            m = RE_FORM.fullmatch(ln)
            if m:
                form = tuple(int(x) for x in m.groups())
                continue
            m = RE_TRIP.fullmatch(ln)
            if m:
                trip = int(m.group(1))
                continue
            m = RE_DD.fullmatch(ln)
            if m:
                dd = int(m.group(1))
                continue
            m = RE_DS.fullmatch(ln)
            if m:
                ds = int(m.group(1))
                continue
            m = RE_OLD.fullmatch(ln)
            if m:
                old = (int(m.group(1)), int(m.group(2)))
                continue
            m = RE_EXIT.fullmatch(ln)
            if m:
                code = int(m.group(1))
                continue
            m = RE_HUNT.fullmatch(ln)
            if m:
                hunt = int(m.group(1))
                continue
            m = RE_K.fullmatch(ln)
            if m:
                k, n, s, u = (int(x) for x in m.groups())
                per_k[k] = (per_k.get(k, (0, 0, 0))[0] + n, max(per_k.get(k, (0, 0, 0))[1], s),
                            max(per_k.get(k, (0, 0, 0))[2], u))
    if done is None:
        print("RULE NOT SATISFIED: %s : no summary line" % path)
        bad += 1
        continue
    samples = done[0]
    tot_samples += samples
    most = max([max(s, u) for (_, s, u) in per_k.values()] + [0])
    name = path.rsplit("/", 1)[-1]
    print("%s : %d : %d : %s : %d : %d : %s : %s : %s : %s : %s : %d : %s : %s" % (
        name, samples, done[2] + done[3], form[0] if form else "-", form[1] if form else "-",
        form[2] if form else "-", trip if trip is not None else "-", dd if dd is not None else "-",
        ds if ds is not None else "-", old[0] if old else "-", old[1] if old else "-", most,
        code if code is not None else "-", hunt if hunt is not None else "-"))
    for k, (n, s, u) in sorted(per_k.items()):
        row = table.setdefault(k, {"n": 0, "s": 0, "u": 0})
        row["n"] += n
        row["s"] = max(row["s"], s)
        row["u"] = max(row["u"], u)
    problem = []
    if done != (samples, samples, 0, 0):
        problem.append("summary %s" % (done,))
    if form is not None and form[1:] != (0, 0):
        problem.append("formula %s" % (form,))
    if trip not in (None, 0):
        problem.append("triples with two signs lost %s" % trip)
    if dd is not None and dd > 1:
        problem.append("doubled doubleton directions %s" % dd)
    if ds is not None and ds > 2:
        problem.append("doubled singleton directions %s" % ds)
    if most > 15:
        problem.append("more than 15 positions: %d" % most)
    if code != 0:
        problem.append("exit code %s" % code)
    if problem:
        bad += 1
        print("RULE NOT SATISFIED: %s : %s" % (path, " ; ".join(problem)))
print("overlap k : samples in the lines of the program : most split : most unsplit")
for k in sorted(table):
    print("%d : %d : %d : %d" % (k, table[k]["n"], table[k]["s"], table[k]["u"]))
print("logs %d, samples %d, failures %d" % (len(sys.argv) - 1, tot_samples, bad))
if bad or not table:
    sys.exit(1)
