"""Third count of the missing positions for the matrices of a log of q3_check (Python, other algorithm).

usage: python3 -I work/capset/q0003/q3_crosscheck.py LOG LAYER
The script reads the lines "matrix M" and "direct a b c d" that q3_check pairs wrote with V = 2,
or that "q3_check one LAYER M 0 2000" wrote.  It builds the cap from the construction, applies M,
and counts the missing sums in the same way as q3_check: the positions with no representation
(the intact missing positions) and the classes with one to three representations that the best
puncture set makes empty.  A class is empty when each of its representations has its A point in U
or its S point in V.  The count is a maximum over the pairs or triples of a small table.  It does
not use the loop of q3_check over all puncture sets.  Revision 2 (28 November 2026): revision 1
counted only the classes with one to three representations.  Thus its numbers were different from
the numbers of q3_check for the matrices that have an intact missing position.
"""
import itertools
import sys
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)}


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


def is_cap(pts):
    s = set(pts)
    return len(pts) == 112 and all(tuple((-a[i] - b[i]) % 3 for i in range(6)) not in s for a in pts for b in pts if a != b)


def image(t, pts):
    return [tuple(sum(t[i][j] * p[j] for j in range(6)) % 3 for i in range(6)) for p in pts]


def key(xs):
    return tuple(sorted(xs))


def best_of_pairs(base, singles, pairs):
    """maximum over pairs U of base + pairs[U] + sum of singles on U"""
    top = sorted(singles.items(), key=lambda kv: -kv[1])[:2]
    best = base + (sum(v for _, v in top) if len(top) == 2 else 0)
    for (x, y), c in pairs.items():
        val = base + c + singles.get(x, 0) + singles.get(y, 0)
        if val > best:
            best = val
    return best


def four_maxima(A, S):
    """reps[z] lists the representations (index in A, index in S) of z"""
    reps = {}
    for ia, a in enumerate(A):
        for js, s in enumerate(S):
            z = tuple((a[i] + s[i]) % 3 for i in range(6))
            reps.setdefault(z, []).append((ia, js))
    cands = [z for z, r in reps.items() if len(r) <= 3]
    out = []
    for nu, nv in ((3, 0), (2, 1), (1, 2), (0, 3)):
        # side 0 : the larger puncture set is in A.  side 1 : it is in S.
        side = 0 if nu >= nv else 1
        nx, ny = max(nu, nv), min(nu, nv)
        xpts = A if side == 0 else S
        ypts = S if side == 0 else A
        best = 0
        if ny == 0:
            t3, p2, s1, base = Counter(), Counter(), Counter(), 0
            for z in cands:
                ends = key({r[side] for r in reps[z]})
                if len(ends) == 3:
                    t3[ends] += 1
                elif len(ends) == 2:
                    p2[ends] += 1
                elif len(ends) == 1:
                    s1[ends[0]] += 1
                else:
                    base += 1
            for u in itertools.combinations(range(len(xpts)), 3):
                val = base + t3.get(u, 0) + p2.get((u[0], u[1]), 0) + p2.get((u[0], u[2]), 0) + p2.get((u[1], u[2]), 0)
                val += s1.get(u[0], 0) + s1.get(u[1], 0) + s1.get(u[2], 0)
                best = max(best, val)
        else:
            for y in range(len(ypts)):
                p2, s1, base = Counter(), Counter(), 0
                for z in cands:
                    ends = key({r[side] for r in reps[z] if r[1 - side] != y})
                    if len(ends) == 2:
                        p2[ends] += 1
                    elif len(ends) == 1:
                        s1[ends[0]] += 1
                    elif not ends:
                        base += 1
                best = max(best, best_of_pairs(base, s1, p2))
        out.append(best)
    # a position with no representation is a missing sum before the punctures
    return out, len(cands), len(set(A) & set(S)), 729 - len(reps)


log, layer = sys.argv[1], int(sys.argv[2])
A = cap(layer)
assert is_cap(A), "the construction does not give a cap"
lines = [l.replace(",", "").split() for l in open(log).read().splitlines()]
pairs = [(l[1], [int(x) for x in lines[i + 1][1:5]]) for i, l in enumerate(lines[:-1]) if l[0] == "matrix" and lines[i + 1][0] == "direct"]
good = 0
for m, claimed in pairs:
    t = [[int(m[6 * i + j]) for j in range(6)] for i in range(6)]
    got, ncand, k, old = four_maxima(A, image(t, A))
    total = [old + g for g in got]
    ok = total == claimed
    good += ok
    print(f"matrix {m} k {k} candidates {ncand} intact missing {old} : python total {total} new {got} : q3_check {claimed} : agree {ok}", flush=True)
print(f"matrices {len(pairs)}, matrices with the same four numbers {good}")
