"""Replay: python -B aba_replay_311_312.py EVIDENCE OUTPUT.json.gz (C++17 compiler).

Compiles the two adjacent .cpp files in a temporary directory. Source data are
rebuilt from the session 303 transcription/dictionary loader and compared with
the session 304 graph. No plaintext, word choice or outcome is supplied to the
solvers. Extra graph controls are checked by permutations of a four-letter alphabet.
"""
import sys,subprocess,gzip,json,random,math,itertools,os,tempfile
from collections import Counter
from pathlib import Path
def run(d):
 sys.path.insert(0,str(d))
 from shortkey_303 import inp
 r,k,v,L=inp(d);e=sorted({(w[0],w[1]) for *_,w in r});t=sorted({(p[0],p[1]) for p in v if p[0]==p[2]!=p[1]})
 old=json.loads(gzip.decompress((d/'graph_304_results.json.gz').read_bytes()))
 assert [list(x) for x in e]==old['source_edges'] and [list(x) for x in t]==old['target']
 def stdin(e,t):return f'{len(e)} {len(t)}\n'+''.join(f'{a} {b}\n' for a,b in [*e,*t])
 with tempfile.TemporaryDirectory() as tmp:
  q=Path(tmp);sf=Path(__file__).resolve().parent
  ex={}
  for name in ('aba_fit_311','aba_audit_311'):
   ex[name]=q/name;subprocess.run([os.environ.get('CXX','c++'),'-O3','-std=c++17',str(sf/(name+'.cpp')),'-o',str(ex[name])],check=True)
  def invoke(src,args,e,t):
   return json.loads(subprocess.check_output([ex[src],*map(str,args)],input=stdin(e,t).encode()))
  # Intersect all edges with a four-label target; mapping unused or unmatched
  # source labels outside those four cannot improve on filling leftover slots.
  rng=random.Random(3301311);U=[(a,b) for a in range(4) for b in range(4) if a!=b]
  cases=0
  for j in range(36):
   A=sorted(rng.sample(U,rng.randint(3,9)));B=sorted(rng.sample(U,rng.randint(2,10)));BG=set(B)
   scores=[{i for i,(a,b) in enumerate(A) if (p[a],p[b]) in BG} for p in itertools.permutations(range(4))]
   maxhits=max(map(len,scores));bestsets={tuple(sorted(x)) for x in scores if len(x)==maxhits};excs=len(A)-maxhits
   trial=invoke('aba_audit_311',[excs],A,B);assert trial['embeddable']==len(bestsets)
   rr=invoke('aba_fit_311',[excs,0,'all'],A,B)
   assert {tuple(i for i in range(len(A)) if not (m>>i&1)) for m,_ in rr['solutions']}==bestsets
   if excs:assert not invoke('aba_fit_311',[excs-1,0],A,B)['compatible']
   cases+=1
  first=invoke('aba_fit_311',[7,24],e,t)
  all8=invoke('aba_fit_311',[8,24,'all'],e,t)
  forced20=invoke('aba_fit_311',[10,24,'one',e.index((22,12))],e,t)
  direct=[invoke('aba_audit_311',[k],e,t) for k in (7,8,9)]
 for z in direct:assert z['deletion_sets']==math.comb(len(e),z['k'])
 assert not first['compatible'] and direct[0]['embeddable']==0
 fp=forced20['permutation'];assert sorted(fp)==list(range(29)) and (fp[22],fp[12]) in t and sum((fp[a],fp[b]) in t for a,b in e)==20
 ts=set(t);results=[];rowct=Counter(w[:2] for *_,w in r)
 for mask,perm in all8.pop('solutions'):
  assert sorted(perm)==list(range(29))
  misses=[i for i,(a,b) in enumerate(e) if (perm[a],perm[b]) not in ts]
  assert len(misses)==8 and mask==sum(1<<i for i in misses)
  results.append(dict(perm=perm,miss_ids=misses,tokens_fit=sum(n for (a,b),n in rowct.items() if (perm[a],perm[b]) in ts)))
 results.sort(key=lambda z:z['miss_ids'])
 assert len(results)==direct[1]['embeddable'] and direct[1]['retained_frequency']==[sum(i not in z['miss_ids'] for z in results) for i in range(len(e))]
 edges=[dict(id=i,outside=L[a],middle=L[b],locations=[list(w[:3]) for w in r if w[3][:2]==(a,b)],tokens=rowct[a,b]) for i,(a,b) in enumerate(e)]
 return dict(letters=L,edges=edges,target=t,small_controls=cases,forced_OE_EO_OE=forced20,negative_search=first,optimal_search=all8,optimal_witnesses=results,direct_audits=direct,notes='Distinct allowed retained subsets are counted, not keys. A feasible set of 21 may be contained in a feasible set of 22. A 29-slot permutation may have unused or unconstrained positions.')
if __name__=='__main__':
 obj=run(Path(sys.argv[1]).resolve())
 Path(sys.argv[2]).write_bytes(gzip.compress((json.dumps(obj,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
