"""python -B row_controls_328.py OUTPUT.json. Python 3.10+. All row values are synthetic."""
import itertools,random,math,json,sys
from functools import reduce
from operator import xor
from collections import Counter
from pathlib import Path
N,T=32,23
names=('sum','xor')
def pred(x,k,m):
 return (sum(x)+k)%256 if m=='sum' else reduce(xor,x,k)
def constants(rows,m):
 return {((r[-1]-sum(r[:7]))%256 if m=='sum' else reduce(xor,r,0)) for r in rows}
def use(rows,m): # Held-out labels read only after passing the gate.
 p=constants(rows[:T],m)
 if len(p)!=1:return None,None
 k=p.pop()
 guess=[pred(r[:7],k,m) for r in rows[T:]]
 return k,sum(g==r[7] for g,r in zip(guess,rows[T:]))
def encoded(payload,m,k):
 def byte(x):
  if m=='sum':
   a=k
   for b in x:a=(a+b)&255
   return a
  # Independent bit-parity construction, distinct from the prediction's reduce(xor).
  return sum((sum((v>>i)&1 for v in [k,*x])%2)<<i for i in range(8))
 return [list(x)+[byte(x)] for x in payload]
def complete(n,rng):
 return [list(rng.randbytes(7)) for i in range(n)]
def engineer(end,k,m,rng):
 rs=[]
 for y in end:
  a=list(rng.randbytes(6))
  a.append((y-k-sum(a))%256 if m=='sum' else reduce(xor,a,k)^y)
  rs+=encoded([a],m,k)
 assert [r[-1] for r in rs]==end
 return rs
def mix(rs,indices):return [r[:7]+[rs[j][7]] for r,j in zip(rs,indices)]
def main():
 rng=random.Random(33010328);data=complete(N,rng);pos={};corrupt={};perm={}
 for m in names:
  other=next(v for v in names if v!=m);ks=[];mistakes=0
  for k in range(256):
   rs=encoded(data,m,k);ans=use(rs,m);a=use(rs,other)
   assert ans==(k,N-T);ks+= [ans[0]];mistakes+=int(a[0] is not None)
  pos[m]=dict(correct_distinct_constants=len(set(ks)),correct_endings=len(ks)*(N-T),rival_admitted=mistakes)
  rs=encoded(data,m,137);ct=Counter()
  for i,col,b in itertools.product(range(N),range(8),range(8)):
   rs[i][col]^=(1<<b)
   p=use(rs,m)
   rs[i][col]^=(1<<b)
   if i<T:assert p==(None,None);ct['train_withheld_not_scored']+=1
   else:assert p==(137,N-T-1);ct['test_one_wrong']+=1
  corrupt[m]=ct
  # Permute just the final bytes of one planted grid, retaining the seven-byte vectors.
  samp=8192;freq=Counter(r[7] for r in rs);admit=Counter();score=0
  for _ in range(samp):
   indices=list(range(N));rng.shuffle(indices);trial=mix(rs,indices)
   score+=sum(x[7]==y[7] for x,y in zip(rs,trial))
   for label in names:
    if use(trial,label)[0] is not None:admit[label]+=1
  perm[m]=dict(samples=samp,admitted={n:admit[n] for n in names},agreement_total=score,
    agreement_expected_per_shuffle_numerator=sum(v*v for v in freq.values()),agreement_expected_per_shuffle_denominator=N,
    original_bytes_unchanged_permutations=math.prod(math.factorial(v) for v in freq.values()),all_permutations=math.factorial(N))
 uniform={m:Counter() for m in names}
 for _ in range(16384):
  seq=rng.randbytes(8*N);rs=[seq[at:at+8] for at in range(0,len(seq),8)]
  for m in names:
   if len(constants(rs[:2],m))==1:uniform[m]['first_two_fit']+=1
   if len(constants(rs[:3],m))==1:uniform[m]['first_three_fit']+=1
   if use(rs,m)[0] is not None:uniform[m]['training_fit']+=1
 ones=[0,0,1,1,2,3,4,5,6];tot=math.factorial(len(ones));hist=Counter()
 for perm9 in itertools.permutations(range(len(ones))):hist[sum(ones[i]==ones[j] for i,j in enumerate(perm9))]+=1
 assert sum(hist.values())==tot and hist[9]==4 and sum(n*v for n,v in hist.items())*9==tot*13
 # Put that duplicate multiset into both real rule mechanisms, then explicitly swap equal vs unequal ends.
 duptests={}
 for m in names:
  rs=engineer(list(range(T))+ones,201,m,rng)
  a=list(range(N));a[T:T+2]=a[T:T+2][::-1]
  equal=use(mix(rs,a),m);a=list(range(N));a[T],a[T+2]=a[T+2],a[T]
  unequal=use(mix(rs,a),m);assert equal==(201,9) and unequal==(201,7)
  duptests[m]=dict(equal_end_swap=equal,unequal_end_swap=unequal)
 # Ambiguous training: each first-page payload has just one nonzero byte (sum == XOR).
 # Both pass, then a carry in every reserved row separates them. Score both, never choose retroactively.
 plain=[]
 for i in range(T):
  x=[0]*7;x[i%7]=1+i;plain.append(x)
 for i in range(N-T):plain.append([1,1,0,0,0,0,0])
 tie=encoded(plain,'sum',0);two={m:use(tie,m) for m in names};assert two==dict(sum=(0,9),xor=(0,0))
 return dict(seed=33010328,training=T,held=N-T,positives=pos,one_bit_damage=corrupt,shuffled_plant=perm,
  uniform=dict(samples=16384,outcomes={m:{k:uniform[m][k] for k in ('first_two_fit','first_three_fit','training_fit')} for m in names},one_rule_gate='2^-176',one_rule_all_32='2^-248'),
  repeated_last_values=dict(sequence=ones,permutation_histogram=hist,tested=tot,swaps=duptests),tied_training=two)
if __name__=='__main__':Path(sys.argv[1]).write_text(json.dumps(main(),sort_keys=True,separators=(',',':'))+'\n')
