"""Offline replay: python -B twins_272_273.py twins_272_273_results.json [--evidence DIR --inputs FILE]. No network."""
from collections import Counter
from itertools import product, combinations, count
from pathlib import Path
import argparse,hashlib,json,math
R='ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ'
L='F U TH O R K G W H N I J EO P X S T B E M L ING OE D A AE Y IO EA'.split()
def sha(b):return hashlib.sha256(b).hexdigest()
def gp(w):return tuple(L.index(c) for s in w for c in s.split())
def xor_idx(a,b):return [i for i,(x,y) in enumerate(zip(a,b,strict=True)) if x!=y]
def seek_primes(n):
 ps=[]
 for i in count(2):
  if all(i%d for d in ps if d*d<=i):ps.append(i)
  if len(ps)==n:return ps

def fullkey(c,y):
 # Index by emitted rune for the audit; None means literal F held and no step consumed.
 assert len(c)==len(y) and all(yi or ci==0 for ci,yi in zip(c,y))
 return [None if yi==0 else (ci-yi)%29 for ci,yi in zip(c,y)]

def encrypt(y,k):
 out=[];s=0;applied=[]
 for ch in y:
  if ch:out.append((ch+k[s])%29);applied.append(k[s]);s+=1
  else:out.append(0);applied.append(None)
 return out,applied

def decode_on_holds(c,k,held):
 out=[];s=0
 for i,ch in enumerate(c):
  if i in held:assert ch==0;out.append(0)
  else:
   y=(ch-k[s])%29;assert y!=0;out.append(y);s+=1
 return out
def visible_matches(c,gold,window):
 # Signed, shifted prime streams. All candidate instructions have the same non-F pattern as gold.
 ps=seek_primes(230);k0=0;idx=[]
 for yi in gold:
  idx.append(k0);k0+=bool(yi)
 known=[i for i,yi in enumerate(gold) if i not in window and yi]
 hold=sorted(i for i,yi in enumerate(gold) if not yi)
 assert not (set(hold)&window)
 ok=[];hist=Counter()
 for start,sign,inter in product(range(128),(1,-1),range(29)):
  wrong=sum((gold[i]+sign*ps[start+idx[i]]+inter)%29!=c[i] for i in known)
  hist[wrong]+=1
  if wrong==0:ok.append([start,sign,inter])
 return ok,hist
def strict_hidden_paths(c,known,mask,k):
 # Fixed documented schedule; require each unmasked plaintext rune, but do not fix any hidden holds, words, or word roles.
 states={(0,()):1};sid=set(mask)
 for i,ch in enumerate(c):
  nxt=Counter()
  for (h,v),n in states.items():
   steps=([(h,0)] if ch==0 else [])+([(h+1,(ch-k[h])%29)] if ch!=k[h] else [])
   for to,w in steps:
    if i in sid or w==known[i]:nxt[to,v+(w,) if i in sid else v]+=n
  states=nxt
 out=Counter()
 for (_,w),n in states.items():out[w]+=n
 return out

def historical(d,inp):
 master=(d/'liber-primus__transcription--master.txt').read_text();cpage=master[master.index('ᚱ-'):].split('%')[71]
 c=[R.index(x) for x in cpage if x in R];groups=json.loads((d/'increment_calibration_sources.json').read_text())['groups']
 gold=next(g['values'] for g in groups if g['name']=='lp2_56')
 assert len(gold)==len(c)==85
 p=[(n-1)%29 for n in seek_primes(100)];enc0,k0=encrypt(gold,p);assert enc0==c
 out=[]
 for w in inp['historical_windows']:
  a,b=w['absolute'];cols=set(range(a,b));base=gp(w['historical']);assert tuple(gold[a:b])==base
  candidate=[w['historical']]+([w['foil']] if 'foil' in w else w['twins']);spec=[]
  if 'followup_unit_shift' in w:candidate.append(w['followup_unit_shift'])
  # Hash the complete non-rune skeleton incl. every printed hex character, punctuation and line boundary.
  skeleton=''.join('·' if x in R else x for x in cpage);masked=bytes(255 if i in cols else x for i,x in enumerate(gold))
  fullobs=sha(bytes(c)+masked+skeleton.encode());vi,fit_hist=visible_matches(c,gold,cols);assert vi==[[0,1,28]]
  real= strict_hidden_paths(c,gold,sorted(cols),p)
  for words in candidate:
   target=gp(words);assert [len(s.split()) for s in words]==w['word_lengths']
   y=gold[:a]+list(target)+gold[b:];kk=fullkey(c,y);k=[v for v in kk if v is not None];zz,zap=encrypt(y,k)
   assert zz==c and decode_on_holds(c,k,{i for i,v in enumerate(kk) if v is None})==y and zap==kk
   assert sha(bytes(zz)+bytes(255 if i in cols else x for i,x in enumerate(y))+skeleton.encode())==fullobs
   hist, _=encrypt(y,p);wrong=xor_idx(hist,c);assert not (set(wrong)-cols)
   spec.append(dict(spelling=[''.join(z.split()) for z in words],key_inside=kk[a:b],plaintext_ordinal=target,
      full_cipher_sha256=sha(bytes(zz)),conditional_observation_sha256=fullobs,
      shifts_changed_from_historical=xor_idx(k0,kk),permitted_by_historical_clock=bool(real[target]),fixed_clock_wrong_positions=wrong))
  pairwise=[]
  for (i,u),(j,v) in combinations(enumerate(spec),2):
   diff=[a+i for i in xor_idx(u['key_inside'],v['key_inside'])]
   deltas=[(v['key_inside'][ix-a]-u['key_inside'][ix-a])%29 for ix in diff]
   pairwise.append(dict(pair=[i,j],required_changed_shifts=diff,n=len(diff),signed_mod29_shift_delta=[v if v<=14 else v-29 for v in deltas]))
  if 'followup_unit_shift' in w:
   rec=next(v for v in pairwise if v['pair']==[1,3]);assert rec['required_changed_shifts']==[71] and rec['signed_mod29_shift_delta']==[-1]
  out.append(dict(name=w['name'],span=[a,b],visible_runes=len(c)-len(cols),choices=spec,comparisons=pairwise,
    fitted_schedules=vi,visible_wrong_count_histogram=dict(sorted(fit_hist.items())),next_best_visible_errors=min(p for p in fit_hist if p),number_of_possible_hidden_strings_under_fitted_clock=len(real),strict_plain_masks_at_fixed_clock=sum(real.values()),
    possible_at_fixed_clock=[dict(gp=[L[i] for i in z],paths=num) for z,num in sorted(real.items())],
    # All ordinary local outputs use one of 28 nonzero runes; a printed F can additionally be a literal hold.
    legal_no_extra_hold_pad_strings=28**len(cols),hidden_printed_F=sorted(i for i in cols if c[i]==0)))
 return out,groups

def signatures(rows,ids):return [tuple(x[i] for i in ids) for x in rows]
def cover(rows):
 n=len(rows[0]);pairs=list(combinations(range(len(rows)),2));masks=[sum((rows[a][i]!=rows[b][i])<<u for u,(a,b) in enumerate(pairs)) for i in range(n)]
 allmask=(1<<len(pairs))-1;stats={};opt=[]
 for r in range(n+1):
  hits=[];mx=0
  for sel in combinations(range(n),r):
   bits=0
   for i in sel:bits|=masks[i]
   mx=max(mx,bits.bit_count())
   if bits==allmask:
    assert len(set(signatures(rows,sel)))==len(rows);hits.append(sel)
  stats[r]=dict(best_pairs_separated=mx,full_subsets=len(hits))
  if hits:opt=hits;break
 return opt,stats,len(pairs)
def synthetic(groups,inp):
 wrds=list(product(*inp['panel']));rows=[gp(w) for w in wrds];assert len(rows)==len(set(rows))==54 and all(len(r)==14 and all(r) for r in rows)
 opts,stats,npair=cover(rows);obs=opts[0];sig=signatures(rows,obs);index=dict(zip(sig,range(len(rows)),strict=True));assert len(index)==len(rows)
 # Separate calibration record: it does not contain one of the hidden target commands.
 warning=next(g['values'] for g in groups if g['name']=='warning');cal=warning[:14];assert all(cal)
 origin=[dict(row=i,words=[''.join(s.split()) for s in w],gp=r) for i,(w,r) in enumerate(zip(wrds,rows))]
 total=success=0;bad=Counter();example=None
 for i,y in enumerate(rows):
  seed=hashlib.sha256(b'witness-273 / fixed calibration A').digest()
  k=[t%29 for t in seed[:14]];c=[(v+j)%29 for v,j in zip(y,k)];c0=[(v+j)%29 for v,j in zip(cal,k)]
  measured=[(c0[j]-cal[j])%29 for j in obs];got=tuple((c[j]-v)%29 for j,v in zip(obs,measured));total+=1;success+=index.get(got)==i
  for h,pos in enumerate(obs):
   for delta in range(1,29):
    ref=list(measured);ref[h]=(ref[h]+delta)%29;pred=tuple((c[j]-v)%29 for j,v in zip(obs,ref));where=index.get(pred)
    bad['abstain' if where is None else ('correct' if where==i else 'false_panel_wording')]+=1
  if i==0:
   example=dict(key_commit_sha256=sha(bytes(k)),known_calibration_ordinals=cal,probe_positions=obs,calibration_cipher_observed=[c0[j] for j in obs],
    recovered_shifts=measured,target_cipher=c,decoded_measured_ordinals=got,decoded_index=index[got],true_words=origin[i]['words'])
 assert success==total and sum(bad.values())==54*4*28
 # Same calibration key for all labels within a run; cross two additional keys
 # against every command. No association between key identity and target identity.
 crossed=[]
 for tag in ['B','C']:
  k=[v%29 for v in hashlib.sha256(('witness-273 / fixed calibration '+tag).encode()).digest()[:14]];c0=[(v+j)%29 for v,j in zip(cal,k)]
  probed=[(c0[j]-cal[j])%29 for j in obs];correct=0
  for rr,y in enumerate(rows):
   cipher=[(v+j)%29 for v,j in zip(y,k)]
   correct+=index.get(tuple((cipher[i]-v)%29 for i,v in zip(obs,probed)))==rr
  assert correct==len(rows);crossed.append(dict(key_sha256=sha(bytes(k)),n=len(rows),correct=correct))
 outsider=gp(inp['outside_panel'])
 assert outsider not in rows
 pred=index[tuple(outsider[j] for j in obs)]
 # Use same ciphertext and identical measured shifts even for this unlisted alternative.
 cc=example['target_cipher'];z=[(c-v)%29 for c,v in zip(cc,outsider)]
 assert all(z[j]==h for j,h in zip(obs,example['recovered_shifts'])) and [(x+y)%29 for x,y in zip(outsider,z)]==cc
 # Same constrained key, generate the unlisted command; closed-panel decoder observing only probes gives same false label.
 k=[a%29 for a in hashlib.sha256(b'witness-273 / fixed calibration A').digest()[:14]];co=[(y+v)%29 for y,v in zip(outsider,k)]
 assert all(co[j]==cc[j] for j in obs) and any(co[j]!=cc[j] for j in range(14))
 # Practical difference between specifying the role only and naming all words.
 verbs=[gp([w]) for w in inp['panel'][0]];act,_,_=cover(verbs)
 return dict(inputs=origin,total_pairs=npair,all_optimal_probe_sets=opts,coarse_verb_optimal_sets=act,
     lex_first_optimum=obs,probes_separation_by_budget=stats,planted=dict(correct=success,tests=total,additional_crossed_calibrations=crossed,calibration_source='First 14 LP1 Warning plaintext rune ordinals, newly enciphered under the same artificial period-14 key at phase zero',example=example),
     corruption_counts=bad,outer=dict(constructed=inp['outside_panel'],closed_panel_prediction=origin[pred]['words'],same_full_cipher_free_unsampled_shifts=z,
      unmeasured_positions_differing_from_which_panel_key=xor_idx(z,k),same_key_new_cipher_changes=xor_idx(cc,co)),
     free_non_F_completions_after_four_probes=28**(14-len(obs)))
def main():
 p=argparse.ArgumentParser();p.add_argument('out',type=Path);p.add_argument('--evidence',type=Path,default=Path(__file__).resolve().parent);p.add_argument('--inputs',type=Path,default=Path(__file__).with_name('twins_272_273_inputs.json'));a=p.parse_args();inps=json.loads(a.inputs.read_text());one,groups=historical(a.evidence,inps);out=dict(controls=one,probes=synthetic(groups,inps),source_sha256={f:sha((a.evidence/f).read_bytes()) for f in ['liber-primus__transcription--master.txt','increment_calibration_sources.json']},input_sha256=sha(a.inputs.read_bytes()))
 a.out.write_text(json.dumps(out,indent=2,sort_keys=True)+'\n')
if __name__=='__main__':main()
