"""Recount lines of SA sets; analyse the complement (size m = 81-n) and profile structure."""
import re, sys, itertools
from math import comb

def dec(i): return (i // 27, (i // 9) % 3, (i // 3) % 3, i % 3)
def enc(t): return t[0] * 27 + t[1] * 9 + t[2] * 3 + t[3]
def third(x, y): return enc(tuple((6 - a - b) % 3 for a, b in zip(dec(x), dec(y))))

def lines(S):
    s = set(S); c = 0
    for x, y in itertools.combinations(S, 2):
        if third(x, y) in s: c += 1
    return c // 3

def classes():
    out = []
    seen = set()
    for xi in itertools.product(range(3), repeat=4):
        if any(xi):
            m = tuple((-a) % 3 for a in xi)
            if m in seen: continue
            seen.add(xi); out.append(xi)
    return out

W = classes()
def profile(S, xi):
    k = [0, 0, 0]
    for x in S: k[sum(a * b for a, b in zip(dec(x), xi)) % 3] += 1
    return tuple(sorted(k, reverse=True))

for line in open(sys.argv[1]):
    m = re.match(r"n=(\d+) best=(\d+) set=(.*)", line)
    if not m: continue
    n, best = int(m.group(1)), int(m.group(2))
    S = list(map(int, m.group(3).split()))
    assert len(S) == n
    L = lines(S)
    comp = [i for i in range(81) if i not in set(S)]
    Lc = lines(comp)
    mm = 81 - n
    assert L == 1080 - 40 * mm + comb(mm, 2) - Lc
    profs = sorted(set(profile(S, xi) for xi in W), reverse=True)
    print(f"n={n} L={L} (claimed {best}) complement m={mm} has {Lc} lines; most-unbalanced profiles: {profs[:3]}")
