"""Third implementation of the union-of-masks tables of IIS-Q-0003 (Python, standard library only).

usage: python3 -I q3_tables_py.py LOGDIR COLLECT
       python3 -I q3_tables_py.py LOGDIR LAYER KIND BUDGETS SETS PART N
LOGDIR is the directory of the logs of q3_check.  The program builds the cap from the construction
of Edel and Bierbrauer, makes the masks with its own code, and counts the families of external
directions with a union of at most BUDGET classes.  A count is the number of families of one size.
The row of a puncture set stops at the size with count 0.  The program compares each row with the
row of q3_check for the same puncture set, the same layer and the same budget.
KIND is intact, dual, p1w (the weak rule for one puncture), p1s (the strict rule for one
puncture), p2 or p3 (the strict rule).
SETS is all (each puncture set) or orbits (one set of each orbit of the puncture sets under the
signed permutation matrices that preserve the cap).  A symmetry of the cap maps classes to
classes, edges to edges and D to D.  Thus all sets of an orbit have the same row.
PART and N: the program takes the work items with number PART, PART + N, PART + 2 N, ...
LAYER -1 selects the complete list of work items of run_tables_py.sh.
"""
import glob
import itertools
import re
import sys
import time
from collections import Counter

DESIGN = {(0, 1, 2), (0, 1, 3), (0, 2, 4), (0, 3, 5), (0, 4, 5), (1, 2, 5), (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 3, 5)}
POW3 = [3 ** i for i in range(6)]
BUDGETS = {"intact": [32, 33, 34, 35, 36, 39, 40, 42, 43], "dual": list(range(30, 41)) + [42, 43],
           "p1w": [36, 38, 39, 41, 42], "p1s": [36, 38, 39, 41, 42], "p2": [34, 35, 36, 37, 38],
           "p3": [32, 33, 34, 35, 36]}
SIZES = {"intact": 0, "dual": 0, "p1w": 1, "p1s": 1, "p2": 2, "p3": 3}
# kind and mode of the work items of run_tables_py.sh, in the order of importance
MODES = [("intact", "all"), ("dual", "all"), ("p1w", "orbits"), ("p1s", "orbits"), ("p3", "orbits"),
         ("p2", "all"), ("p1w", "all"), ("p1s", "all")]
NCLASSES = 56
MAXD = 13

CO = [[(v // POW3[i]) % 3 for i in range(6)] for v in range(729)]
NEG = [sum(((3 - CO[v][i]) % 3) * POW3[i] for i in range(6)) for v in range(729)]


def vec(x):
    return sum(x[i] * POW3[i] for i in range(6))


def cap(layer):
    pts = set()
    for v in range(729):
        x = CO[v]
        support = tuple(i for i in range(6) if x[i])
        if len(support) == 6 and x.count(2) % 2 == 0:
            pts.add(v)
        elif len(support) == 3 and (support in DESIGN) == (layer == 0):
            pts.add(v)
    return pts


def dot(a, b):
    return sum(CO[a][i] * CO[b][i] for i in range(6)) % 3


def structure(layer):
    """The cap, its 56 projective classes, the 308 external directions with their edges, and D."""
    pts = cap(layer)
    assert len(pts) == 112, "the construction does not give 112 points"
    assert all(NEG[p] in pts for p in pts), "the cap is not antipodal"
    for a, b in itertools.combinations(pts, 2):
        c = vec([(CO[a][i] + CO[b][i]) % 3 for i in range(6)])
        assert NEG[c] not in pts, "the cap has a line"
    lead = [next((i for i in range(6) if CO[v][i]), None) for v in range(729)]
    rep = [v if lead[v] is None or CO[v][lead[v]] == 1 else NEG[v] for v in range(729)]
    allreps = [v for v in range(1, 729) if rep[v] == v]
    R = [v for v in allreps if v in pts]
    assert len(R) == NCLASSES, "the cap does not have 56 projective classes"
    ridx = {v: i for i, v in enumerate(R)}
    ext = [v for v in allreps if v not in pts]
    assert len(ext) == 308, "the number of external directions is not 308"
    edges = []
    for z in ext:
        ez = set()
        for x in pts:
            y = vec([(CO[x][i] + CO[z][i]) % 3 for i in range(6)])
            if y in pts:
                i, j = ridx[rep[x]], ridx[rep[y]]
                ez.add((i, j) if i < j else (j, i))
        assert len(ez) == 10, "an external direction has not 10 edges"
        edges.append(sorted(ez))
    D = [w for w in range(1, 729) if sum(1 for x in pts if dot(x, w) == 0) == 22]
    assert len(D) == 112 and all(NEG[w] in D for w in D), "the set D has not 112 points"
    DR = [v for v in allreps if v in D]
    assert len(DR) == NCLASSES, "the set D does not have 56 projective classes"
    return pts, R, ridx, rep, ext, edges, DR


def primal_masks(edges, punct, weak):
    """Marks of each direction.  punct is a set of punctured projective classes.
    weak: an edge with a punctured endpoint loses both endpoints.  strict: an endpoint loses its
    mark when its partner on the edge is punctured."""
    out = []
    for ez in edges:
        m = 0
        for a, b in ez:
            if not punct:
                m |= (1 << a) | (1 << b)
            elif weak:
                if a not in punct and b not in punct:
                    m |= (1 << a) | (1 << b)
            else:
                if a not in punct:
                    m |= 1 << b
                if b not in punct:
                    m |= 1 << a
        out.append(m)
    return out


def dual_masks(ext, DR):
    out = []
    for z in ext:
        m = 0
        for i, d in enumerate(DR):
            if dot(d, z) == 0:
                m |= 1 << i
        assert m.bit_count() == 40, "a dual mask has not 40 marks"
        out.append(m)
    return out


def symmetries(pts, R, ridx, rep, layer):
    """The signed permutation matrices that preserve the cap, as permutations of the 56 classes.
    The image of the point x is y with y_i = signs_i * x_perm(i)."""
    out = []
    odd = 0
    for perm in itertools.permutations(range(6)):
        for signs in itertools.product((1, 2), repeat=6):
            good = True
            for x in pts:
                cx = CO[x]
                y = sum((signs[i] * cx[perm[i]] % 3) * POW3[i] for i in range(6))
                if y not in pts:
                    good = False
                    break
            if good:
                odd += signs.count(2) % 2
                perm_cls = []
                for v in R:
                    cv = CO[v]
                    y = sum((signs[i] * cv[perm[i]] % 3) * POW3[i] for i in range(6))
                    perm_cls.append(ridx[rep[y]])
                out.append(tuple(perm_cls))
    print("layer %d: %d signed permutation matrices preserve the cap, %d with an odd number of sign changes, "
          "%d different permutations of the classes" % (layer, len(out), odd, len(set(out))), flush=True)
    return out


def closure_size(gens, n):
    """The size of the group that the permutations gens make on the numbers 0 .. n-1."""
    seen = {tuple(range(n))}
    stack = [tuple(range(n))]
    while stack:
        t = stack.pop()
        for g in gens:
            u = tuple(g[c] for c in t)
            if u not in seen:
                seen.add(u)
                stack.append(u)
    return len(seen)


def generating_set(group, n):
    """A small list of elements of the group that make the full group of the permutations of the
    classes.  Two matrices can give the same permutation of the classes."""
    order = len(set(group))
    gens = []
    size = 1
    for g in set(group):
        if g == tuple(range(n)):
            continue
        trial = gens + [g]
        new = closure_size(trial, n)
        if new > size:
            gens, size = trial, new
            if size == order:
                return gens
    return [] if order == 1 else None


def orbit_representatives(sets, group):
    """One set of each orbit of the sets under the group, with the complete orbit.
    The representative is the first set of the orbit in the order of the list."""
    n = len(group[0])
    gens = generating_set(group, n)
    assert gens is not None, "the generating set is not found"
    seen = set()
    out = []
    for s in sets:
        if s in seen:
            continue
        orb = {s}
        stack = [s]
        while stack:
            t = stack.pop()
            for g in gens:
                u = tuple(sorted(g[c] for c in t))
                if u not in orb:
                    orb.add(u)
                    stack.append(u)
        assert orb <= seen | set(sets), "an orbit leaves the list of the puncture sets"
        seen |= orb
        out.append((s, frozenset(orb)))
    return out


def families(masks, budget):
    """counts[d] is the number of families of d directions with a union of at most budget marks."""
    pm = masks
    bc = int.bit_count
    cnt = [0] * (MAXD + 1)

    def walk(u, cand, depth):
        n = len(cand)
        for i in range(n):
            v = u | pm[cand[i]]
            cnt[depth + 1] += 1
            nxt = [cand[j] for j in range(i + 1, n) if bc(v | pm[cand[j]]) <= budget]
            if nxt and depth + 1 < MAXD:
                walk(v, nxt, depth + 1)

    walk(0, [e for e in range(len(pm)) if bc(pm[e]) <= budget], 0)
    return tuple(cnt[1:next((d for d in range(1, MAXD + 1) if cnt[d] == 0), MAXD + 1) + 1])


def parse_tail(tail):
    out, budget = {}, None
    for tok in re.findall(r"\d+:|\d+", tail):
        if tok.endswith(":"):
            budget = int(tok[:-1])
            out[budget] = []
        else:
            out[budget].append(int(tok))
    return {b: tuple(c) for b, c in out.items()}


def c_rows(logdir, layer, kind):
    """The rows of q3_check: (puncture set) -> {budget: counts}."""
    names = ["q3_%s_L%d.log" % (kind, layer)] if kind in ("intact", "dual", "p1w", "p1s") else None
    files = [logdir + "/" + n for n in names] if names else sorted(glob.glob("%s/q3_%s_L%d_*.log" % (logdir, kind, layer)))
    out = {}
    for path in files:
        with open(path, encoding="utf-8") as f:
            for ln in f:
                ln = ln.rstrip("\n")
                if "|" in ln:
                    head, tail = ln.split("|", 1)
                    fields = head.split()
                    assert fields[0] == kind, "a line of another kind in %s" % path
                    out[tuple(int(x) for x in fields[1:])] = parse_tail(tail)
                elif kind in ("intact", "dual") and re.match(r"\s*\d+:", ln):
                    out[()] = parse_tail(ln)
    return out


def items_of(layer, kind, mode, group):
    n = SIZES[kind]
    if n == 0:
        return [(layer, kind, "all", (), frozenset())]
    sets = list(itertools.combinations(range(NCLASSES), n))
    reps = [(s, frozenset()) for s in sets] if mode == "all" else orbit_representatives(sets, group)
    return [(layer, kind, mode, s, orb) for s, orb in reps]


def work_items(groups):
    items = []
    for kind, mode in MODES:
        for layer in (0, 1):
            if mode == "all" and kind in ("p1w", "p1s") and layer == 1:
                continue  # the second layer has the orbit representatives of these two kinds only
            items += items_of(layer, kind, mode, groups[layer])
    return items


def run(logdir, layer_sel, kind_sel, budgets_sel, sets_mode, part, nparts):
    t0 = time.time()
    groups = {}
    structs = {}
    layers = (0, 1) if layer_sel == -1 else (layer_sel,)
    for layer in layers:
        structs[layer] = structure(layer)
        groups[layer] = symmetries(structs[layer][0], structs[layer][1], structs[layer][2], structs[layer][3], layer)
    if layer_sel == -1:
        items = work_items(groups)
    else:
        items = items_of(layer_sel, kind_sel, sets_mode, groups[layer_sel])
    counts = {}
    for l, k, m, _, orb in items:
        c = counts.setdefault((l, k, m), [0, 0])
        c[0] += 1
        c[1] += 1 if not orb else len(orb)
    for key in sorted(counts):
        print("ITEMS layer %d %s mode %s : representatives %d : sets %d" % (
            key[0], key[1], key[2], counts[key][0], counts[key][1]), flush=True)
    mine = items[part::nparts]
    print("work items %d, items of this part %d" % (len(items), len(mine)), flush=True)
    n_rows = n_same = n_diff = n_sets = n_const = 0
    refs = {}
    for layer, kind, mode, s, orb in mine:
        pts, R, ridx, rep, ext, edges, DR = structs[layer]
        masks = dual_masks(ext, DR) if kind == "dual" else primal_masks(edges, set(s), kind == "p1w")
        if layer not in refs:
            refs[layer] = {k: c_rows(logdir, layer, k) for k in SIZES}
        ref = refs[layer][kind]
        size = len(orb) if orb else 1
        n_sets += size
        if orb:
            # the rows of q3_check must be the same for all sets of the orbit
            n_const += all(ref[t] == ref[s] for t in orb)
        parts = []
        same = True
        for b in budgets_sel or BUDGETS[kind]:
            row = families(masks, b)
            n_rows += 1
            if row != ref[s][b]:
                same = False
                n_diff += 1
            else:
                n_same += 1
            parts.append("%d: %s" % (b, " ".join(str(c) for c in row)))
        print("ROW layer %d %s mode %s set %s orbit %d : %s : same as q3_check %s" % (
            layer, kind, mode, str(s), size, " : ".join(parts), same), flush=True)
    print("python tables part %d of %d: items %d, sets %d, table rows %d, rows same as q3_check %d, rows different %d, "
          "orbits with one row in q3_check %d, seconds %d" % (
              part, nparts, len(mine), n_sets, n_rows, n_same, n_diff, n_const, round(time.time() - t0)), flush=True)
    return 1 if n_diff or n_const != sum(1 for _, _, _, _, orb in mine if orb) else 0


def collect(logdir):
    re_row = re.compile(r"ROW layer (\d+) (\w+) mode (\w+) set \(([\d, ]*)\) orbit (\d+) : (.*) : same as q3_check (True|False)$")
    re_sum = re.compile(r"python tables part (\d+) of (\d+): items (\d+), sets (\d+), table rows (\d+), rows same as q3_check (\d+), rows different (\d+), orbits with one row in q3_check (\d+), seconds (\d+)$")
    re_grp = re.compile(r"layer (\d+): (\d+) signed permutation matrices preserve the cap, (\d+) with an odd number of sign changes, (\d+) different permutations of the classes$")
    re_items = re.compile(r"ITEMS layer (\d+) (\w+) mode (\w+) : representatives (\d+) : sets (\d+)$")
    re_exit = re.compile(r"exit (\d+)$")
    re_name = re.compile(r"q3_tables_py_P(\d+)\.log$")
    problems = []
    group = {}
    expected = {}
    kinds = {}
    seen = set()
    complete = incomplete = 0
    total = [0, 0, 0, 0, 0]
    longest = 0
    nparts = None
    parts = []
    logs = sorted(glob.glob("%s/q3_tables_py_P*.log" % logdir), key=lambda p: int(re_name.search(p).group(1)))
    for path in logs:
        name = path.rsplit("/", 1)[-1]
        number = int(re_name.search(path).group(1))
        if number >= len(logs):
            problems.append("%s has a part number that is too large" % name)
        with open(path, encoding="utf-8") as f:
            lines = [ln.rstrip("\n") for ln in f]
        sums = [m for m in (re_sum.fullmatch(ln) for ln in lines) if m]
        codes = [int(m.group(1)) for ln in lines for m in [re_exit.search(ln)] if m]
        done = len(sums) == 1 and codes == [0]
        if done:
            complete += 1
            s = sums[0]
            nparts = int(s.group(2)) if nparts is None else nparts
            parts.append(int(s.group(1)))
            if int(s.group(2)) != nparts or int(s.group(1)) != number:
                problems.append("%s is not the log of the part with its number" % name)
            for i in range(5):  # items, sets, table rows, rows same, rows different
                total[i] += int(s.group(3 + i))
            longest = max(longest, int(s.group(9)))
        else:
            incomplete += 1
            if sums or codes:
                problems.append("%s has no exit code 0 or has more than one final line" % name)
        for m in (m for m in (re_grp.fullmatch(ln) for ln in lines) if m):
            key = int(m.group(1))
            if group.setdefault(key, [int(m.group(i)) for i in (2, 3, 4)]) != [int(m.group(i)) for i in (2, 3, 4)]:
                problems.append("%s gives other numbers of symmetries" % name)
        for m in (m for m in (re_items.fullmatch(ln) for ln in lines) if m):
            key = (int(m.group(1)), m.group(2), m.group(3))
            if expected.setdefault(key, [int(m.group(4)), int(m.group(5))]) != [int(m.group(4)), int(m.group(5))]:
                problems.append("%s gives another number of work items" % name)
        for m in (m for m in (re_row.fullmatch(ln) for ln in lines) if m):
            key = (int(m.group(1)), m.group(2), m.group(3))
            skey = key + (m.group(4),)
            if skey in seen:
                problems.append("%s repeats a puncture set" % name)
            seen.add(skey)
            k = kinds.setdefault(key, [0, 0, 0, 0])
            k[0] += 1
            k[3] += int(m.group(5))
            if m.group(7) == "True":
                k[1] += 1
            else:
                k[2] += 1
    if not logs:
        problems.append("no log")
    if complete and sorted(parts) != list(range(len(logs))):
        problems.append("the numbers of the complete parts are not 0 .. %d" % (len(logs) - 1))
    if incomplete and nparts != len(logs):
        problems.append("the number of the processes %s is not the number of the logs %d" % (nparts, len(logs)))
    for layer in sorted(group):
        print("layer %d: %d signed permutation matrices preserve the cap, %d with an odd number of sign changes, "
              "%d different permutations of the classes" % (layer, group[layer][0], group[layer][1], group[layer][2]))
    print("layer : kind : mode : representatives done : sets done : sets expected : table rows same as q3_check : table rows different : all puncture sets")
    for key in sorted(kinds):
        k = kinds[key]
        nsets = 1 if SIZES[key[1]] == 0 else len(list(itertools.combinations(range(NCLASSES), SIZES[key[1]])))
        print("%d : %s : %s : %d : %d : %s : %d : %d : %d" % (
            key[0], key[1], key[2], k[0], k[3], expected.get(key, ["-", "-"])[1], k[1], k[2], nsets))
    print("python tables: logs %(logs)d, complete logs %(complete)d, incomplete logs %(incomplete)d, parts %(parts)s, "
          "work items %(items)d of %(items_all)d, sets %(sets)d of %(sets_all)d, table rows %(rows)d, "
          "rows same as q3_check %(same)d, rows different %(different)d, seconds of the longest complete part %(seconds)d, "
          "problems %(problems)d" % {
              "logs": len(logs), "complete": complete, "incomplete": incomplete, "parts": nparts,
              "items": total[0], "items_all": sum(v[0] for v in expected.values()),
              "sets": total[1], "sets_all": sum(v[1] for v in expected.values()),
              "rows": total[2], "same": total[3], "different": total[4],
              "seconds": longest, "problems": len(problems)})
    for name in problems:
        print("PROBLEM: %s" % name)
    return 1 if problems or total[4] else 0


def main():
    logdir = sys.argv[1]
    if sys.argv[2] == "COLLECT":
        return collect(logdir)
    layer, kind = int(sys.argv[2]), sys.argv[3]
    budgets = [int(x) for x in sys.argv[4].split(",")] if sys.argv[4] != "-" else None
    return run(logdir, layer, kind, budgets, sys.argv[5], int(sys.argv[6]), int(sys.argv[7]))


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