"""Collect the union-of-masks tables of q3_check and compare them with the replay of the author.

usage: python3 -I work/capset/q0003/collect_tables.py LOGDIR
The script reads only the logs of this round. It writes nothing.
"""
import re
import sys
from collections import Counter
from pathlib import Path

logdir = Path(sys.argv[1])
row = re.compile(r"(\d+):((?: \d+)+)")
author = {"dual": {37: 3, 39: 3, 43: 6}, "0": {35: 2, 39: 3, 43: 6},
          "1": {36: 3, 38: 4, 39: 6, 41: 6, 42: 9}, "2": {35: 3, 36: 4, 37: 5},
          "3": {34: 4, 35: 5, 36: 5}}
mine = {"dual": "dual", "intact": "0", "p1w": "1", "p2": "2", "p3": "3"}


def parse(text):
    out = []
    for line in text.splitlines():
        rest = line.split("|", 1)[1] if "|" in line else line
        parts = re.split(r"(\d+):", rest)
        rows = []
        for i in range(1, len(parts) - 1, 2):
            rows.append((int(parts[i]), tuple(int(x) for x in parts[i + 1].split())))
        if rows:
            out.append(rows)
    return out


def longest(counts):
    n = 0
    for c in counts:
        if not c:
            break
        n += 1
    return n


def load(layer, kind):
    files = sorted(logdir.glob(f"q3_{kind}_L{layer}*.log"))
    if kind == "p1w":
        files = [logdir / f"q3_p1w_L{layer}.log"]
    if kind == "intact":
        files = [logdir / f"q3_intact_L{layer}.log"]
    table = {}
    for f in files:
        if f.name.endswith("_run.log"):
            continue
        for rows in parse(f.read_text()):
            for budget, counts in rows:
                table.setdefault(budget, Counter())[counts] += 1
    return table


bad = 0
for layer in (0, 1):
    print(f"layer {layer}")
    # p1s is my stricter variant of the one-puncture mask; the author has no row for it
    for kind in ("intact", "dual", "p1w", "p1s", "p2", "p3"):
        table = load(layer, kind)
        budgets = sorted(table)
        print(f"  {kind}: budget : maximum directions : number of distinct rows : number of sets")
        print("    " + "  ".join(f"{b}:{max(longest(c) for c in table[b])}:{len(table[b])}:{sum(table[b].values())}" for b in budgets))
        key = mine.get(kind)
        if key is None:
            continue
        for b, claimed in author[key].items():
            rows = table.get(b)
            if rows is None:
                print(f"    no row for author budget {b}")
                bad += 1
                continue
            got = max(longest(c) for c in rows)
            ok = got == claimed
            bad += not ok
            print(f"    author budget {b} : author maximum {claimed} : my maximum {got} : agree {ok}")
print(f"disagreements with the author: {bad}")
for layer in (0, 1):
    same = True
    for kind in ("intact", "dual", "p1w", "p1s", "p2", "p3"):
        same &= load(0, kind) == load(1, kind)
    print(f"layer 0 and layer 1 give identical rows for all six types: {same}")
