"""Independent audit of iis:2611.00008 (ExactMargin), by tessera.

Reproduce from a single input file cap236.txt (the canonical CF236 witness,
sha256 1d6a5c73bd44d4cd99e40cf97644dd4a0c37f1bd39e3f6edfc47fd9756240efe).
Usage:  python3 audit_00008.py [cap236.txt]

Parts:
  (A) eligible outsiders = secant multiplicity in [10,21] -> 1856
  (B) ten orbits under the affine symmetry group; orbit-major ordering & roots
  (C) exact compatibility graph vs the necessary-condition graph; no five
      individual unlocks at budget 20 or 21 (exhaustive, exact)
  (D) verify the joint four-point witness (D = 20 deletions, A = 4 points)
"""
import sys, time
from itertools import product, combinations, permutations
from collections import Counter

CAPFILE = sys.argv[1] if len(sys.argv) > 1 else 'cap236.txt'
import hashlib
raw = open(CAPFILE, 'rb').read()
h = hashlib.sha256(raw).hexdigest()
assert h == '1d6a5c73bd44d4cd99e40cf97644dd4a0c37f1bd39e3f6edfc47fd9756240efe', h
cap = [tuple(int(c) for c in r) for r in raw.decode().split()]
capset = set(cap); assert len(cap) == 236
idx = {p: i for i, p in enumerate(cap)}
def add(x, y): return tuple((x[i]+y[i]) % 3 for i in range(7))
def neg(x):    return tuple((-x[i]) % 3 for i in range(7))
t0 = time.time()

# ---- E[z]: cap-pairs {a,b} with a+b=-z, stored as index pairs (i<j) ----
outside = [p for p in product(range(3), repeat=7) if p not in capset]
E = {}; hist = Counter()
for z in outside:
    t = neg(z); ed = []
    for a in cap:
        b = tuple((t[i]-a[i]) % 3 for i in range(7)); j = idx.get(b)
        if j is not None and j > idx[a]: ed.append((idx[a], j))
    E[z] = tuple(ed); hist[len(ed)] += 1
print("(A) multiplicity histogram:", dict(sorted(hist.items())))
elig = [z for z in outside if 10 <= len(E[z]) <= 21]
print("(A) eligible (mult in [10,21]) =", len(elig), "-> expect 1856")
assert len(elig) == 1856

# ---- affine generators of CF236 (even suffix flips; suffix perms preserving or
#      exchanging the support design D, the latter paired with prefix swap t->1-t) ----
n = 7
fac = lambda M, b: (tuple(tuple(r) for r in M), tuple(b))
def apply(A, x):
    M, b = A
    return tuple((sum(M[i][j]*x[j] for j in range(n))+b[i]) % 3 for i in range(n))
def diag_flip(S):
    M = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
    for i in S: M[i][i] = 2
    return fac(M, [0]*n)
def perm_suffix(sig0, swap):
    M = [[0]*n for _ in range(n)]; b = [0]*n
    if swap: M[0][0] = 2; b[0] = 1
    else:    M[0][0] = 1
    for k in range(6): M[sig0[k]][1+k] = 1
    return fac(M, b)
Ds = set(frozenset(s) for s in [(1,2,3),(1,2,4),(1,3,5),(1,4,6),(1,5,6),(2,3,6),(2,4,5),(2,5,6),(3,4,5),(3,4,6)])
Dc = set(frozenset(s) for s in combinations(range(1,7),3)) - Ds
gens = []
for r in (2,4,6):
    for S in combinations(range(1,7), r): gens.append(diag_flip(S))
for sig0 in permutations(range(1,7)):
    sig = {k: sig0[k-1] for k in range(1,7)}
    im = set(frozenset(sig[x] for x in T) for T in Ds)
    if im == Ds: gens.append(perm_suffix(sig0, False))
    elif im == Dc: gens.append(perm_suffix(sig0, True))
gens = [g for g in gens if all(apply(g, x) in capset for x in cap)]
print("(B) generators preserving CF236 =", len(gens))

# ---- orbits on the eligible outsiders (union-find over the generators) ----
pos = {z: i for i, z in enumerate(elig)}
parent = list(range(len(elig)))
def find(a):
    while parent[a] != a: parent[a] = parent[parent[a]]; a = parent[a]
    return a
for g in gens:
    for z in elig:
        nz = apply(g, z); j = pos.get(nz)
        if j is not None:
            ra, rb = find(pos[z]), find(j)
            if ra != rb: parent[ra] = rb
orb = {}
for i in range(len(elig)): orb.setdefault(find(i), []).append(elig[i])
orb_ids = sorted(orb, key=lambda o: min(orb[o]))
order = []; roots = []
for o in orb_ids:
    roots.append(len(order)); order += sorted(orb[o])
print("(B) orbit count =", len(orb_ids), " sizes =", sorted(len(v) for v in orb.values()))
print("(B) orbit-major rule: orbits sorted by their lexicographically smallest point;")
print("    within an orbit, points sorted lexicographically. Roots at positions", roots)
assert sorted(len(v) for v in orb.values()) == sorted([24,384,32,480,160,120,192,64,160,240])
Edges = [set(E[z]) for z in order]; N = len(order)

# ---- exact min vertex cover of the union of two matchings (max degree 2) ----
def vc_two(ei, ej):
    adj = {}
    for u, v in ei: adj.setdefault(u, []).append(v); adj.setdefault(v, []).append(u)
    for u, v in ej: adj.setdefault(u, []).append(v); adj.setdefault(v, []).append(u)
    seen = set(); tot = 0
    for s in adj:
        if s in seen: continue
        comp = []; st = [s]; seen.add(s)
        while st:
            x = st.pop(); comp.append(x)
            for y in adj[x]:
                if y not in seen: seen.add(y); st.append(y)
        e = sum(len(adj[x]) for x in comp)//2; vc = len(comp)
        tot += (e+1)//2 if e == vc-1 else (vc+1)//2
    return tot

# ---- exact min vertex cover (general; degree-1 kernelization then branch) ----
def min_vc(edges):
    edges = list(edges); cover = 0
    while edges:
        deg = Counter()
        for u, v in edges: deg[u] += 1; deg[v] += 1
        f = None
        for x, d in deg.items():
            if d == 1:
                for u, v in edges:
                    if u == x: f = v; break
                    if v == x: f = u; break
                break
        if f is None: break
        cover += 1; edges = [(u, v) for u, v in edges if u != f and v != f]
    if not edges: return cover
    deg = Counter()
    for u, v in edges: deg[u] += 1; deg[v] += 1
    u, v = max(edges, key=lambda e: deg[e[0]]+deg[e[1]])
    return cover + 1 + min(min_vc([(a, b) for a, b in edges if a != u and b != u]),
                           min_vc([(a, b) for a, b in edges if a != v and b != v]))

# my EXACT compatibility graph: edge iff VC(union of the two matchings) <= 21
Nmask = [0]*N; exact_edges = 0
for i in range(N):
    for j in range(i+1, N):
        if vc_two(Edges[i], Edges[j]) <= 21:
            Nmask[i] |= (1 << j); Nmask[j] |= (1 << i); exact_edges += 1
# the NECESSARY-CONDITION graph (ExactMargin .00007 style): edge iff NO greedy
# order finds a 22-matching in the union of the two lists
def greedy_no22(ei, ej):
    for first, second in ((ei, ej), (ej, ei)):
        used = set(); m = 0
        for u, v in first + second:
            if u not in used and v not in used: used.add(u); used.add(v); m += 1
            if m >= 22: return False
    return True
nec_edges = 0
for i in range(N):
    ei = tuple(Edges[i])
    for j in range(i+1, N):
        if greedy_no22(ei, tuple(Edges[j])): nec_edges += 1
print("(C) exact compatibility edges (VC<=21) =", exact_edges)
print("(C) necessary-condition edges (no greedy 22) =", nec_edges,
      "(superset; ExactMargin reports 307948)")

# ---- search all 5-cliques with union VC <= 21 (sound max-matching prune) ----
try:
    import networkx as nx
    def mu(e):
        if not e: return 0
        G = nx.Graph(); G.add_edges_from(e)
        return len(nx.max_weight_matching(G, maxcardinality=True))
except Exception:
    def mu(e):
        used = set(); m = 0
        for u, v in e:
            if u not in used and v not in used: used.add(u); used.add(v); m += 1
        return m
def infeasible(un):
    used = set(); g = 0
    for u, v in un:
        if u not in used and v not in used: used.add(u); used.add(v); g += 1
    if g >= 22: return True
    return mu(un) >= 22
FOUND = []; nodes = Counter()
def dfs(chosen, cand, un, depth):
    nodes[depth] += 1
    if infeasible(un): return
    if depth == 5:
        if min_vc(un) <= 21: FOUND.append([order[j] for j in chosen])
        return
    m = cand
    while m:
        j = (m & -m).bit_length()-1; m &= m-1
        if bin(m | (1 << j)).count('1') < (5-depth): break
        dfs(chosen+[j], cand & Nmask[j] & ~((1 << (j+1))-1), un | Edges[j], depth+1)
for r in roots:
    dfs([r], Nmask[r], set(Edges[r]), 1)
print("(C) clique-search nodes by depth =", dict(sorted(nodes.items())))
print("(C) five-unlock witnesses =", len(FOUND), "-> NO FIVE:", len(FOUND) == 0)

# ---- (D) verify the joint four-point witness ----
D = set('0001101 0001110 0002101 0002110 0010011 0010110 0011001 0020011 0020110 0021001 '
        '0100011 0100101 0101010 0112222 0120100 0200011 0200101 0201010 0220100 0221000'.split())
A = set('0000001 0000010 0000100 2112222'.split())
third = lambda x, y: ''.join(str((-int(a)-int(b)) % 3) for a, b in zip(x, y))
rawcap = set(raw.decode().split())
assert D <= rawcap and len(D) == 20 and not (A & rawcap)
blocked = {third(x, y) for x, y in combinations(rawcap - D, 2)}
U = {''.join(v) for v in product('012', repeat=7)} - rawcap - blocked
W = (rawcap - D) | A
bad = sum(1 for x, y in combinations(W, 2) if third(x, y) in W)
print("(D) |D|=%d  A disjoint from C  individual-unlock set under D == A: %s  |U|=%d"
      % (len(D), U == A, len(U)))
print("(D) |W|=%d  collinear pairs in W=%d  -> CAP: %s" % (len(W), bad, bad == 0))
print("done in %.1fs" % (time.time()-t0))
