"""Session99 frozen real-pair screen. Nineteen null pairs then originals, once."""
from pathlib import Path
import argparse,json,random,hashlib
import numpy as np
import early_anchor_recovery as e
import first_section_recovery as f
from lp_core import lp,vals,R,LET
from lexical_words import tokenize_words
ROOT=e.ROOT
PLAN=ROOT/'real_pair_recovery_next_plan.json'
CASES=ROOT/'real_pair_recovery_cases.json'
SPEC=ROOT/'real_pair_recovery_execution.json'
CHECKS=ROOT/'real_pair_recovery_checks.json'
RESULTS=ROOT/'real_pair_recovery_results.json'
read=e.read;dump=e.dump;sha=e.sha

def archives():
 for n,h in read(PLAN)['input_hashes'].items():assert sha(ROOT/n)==h,n
 e.verify();assert read(e.CHECKS)['passed'] and read(e.RESULTS)['overall_gate']=='pass'

def model():
 m=read(ROOT/'first_section_model.json');return {**m,'log':np.asarray(m['log']),'unigram_log':np.asarray(m['unigram_log'])}

def extract():
 full='%'.join(lp[:56]);sections=full.split('$');data=read(ROOT/'shared_periodic_cases.json');out=[]
 for si,sid in enumerate([6,8]):
  source=sections[sid];cipher=vals(source).tolist();words=tokenize_words(source);pagebase='$'.join(sections[:sid]).count('%')
  s=[0]*len(cipher);t=[0]*len(cipher)
  for w in words:s[w['rune_offset']]=1;t[w['rune_offset']+len(w['values'])-1]=1
  cut=max(i+1 for i,v in enumerate(t) if v and i+1<=int(.6*len(cipher)));anchor=[28,3310][si];mask=[1]*len(cipher);mask[anchor:anchor+6]=[0]*6
  assert cipher==next(v['cipher'] for v in data['real_section_layout'] if v['id']==sid)
  assert (len(cipher),len(words),cut)==[(1524,349,913),(3316,735,1989)][si]
  assert cipher[anchor:anchor+6]==[23,11,1,17,18,10] and s[anchor:anchor+6]==[1,0,0,1,0,0] and t[anchor:anchor+6]==[0,0,1,0,0,1]
  constraints={q['id']:next(v['constraints'] for v in q['sections'] if v['id']==sid) for q in data['queries']}
  singletons=[]
  for w in words:
   if len(w['values'])==1:
    pos=w['rune_offset'];singletons.append({'offset':pos,'LP2_page':pagebase+w['page'],'page_rune_offset':w['page_rune_offset'],'segment':'prefix' if pos<cut else 'continuation','eligible_prior_red_exemptions':str(pos) in constraints['AIO_prior_red_exemptions']})
  out.append({'id':f'original_s{si}','section_id':sid,'stream':si,'kind':'original','source_text':source,'words':words,'singletons':singletons,'constraints':constraints,'cipher':cipher,'starts':s,'ends':t,'score_mask':mask,'cut':cut,'period':13,'decoder_seed':990000+si,'selective_F':True,'anchor_start':anchor,'anchor_length':6})
 return out

def prepare():
 assert not any(p.exists() for p in [CASES,SPEC,CHECKS,RESULTS]);archives();m=model();originals=extract();nulls=[]
 for rep in range(19):
  rng=random.Random(339099+rep);streams=[]
  for c in originals:
   cipher=c['cipher'].copy()
   for lo,hi in [(0,c['cut']),(c['cut'],len(cipher))]:
    ix=[i for i in range(lo,hi) if c['score_mask'][i]];vs=[cipher[i] for i in ix];rng.shuffle(vs)
    for i,v in zip(ix,vs):cipher[i]=v
   n={**e.public_case(c),'id':f'null{rep:02d}_s{c["stream"]}','stream':c['stream'],'section_id':c['section_id'],'kind':'null','anchor_start':c['anchor_start'],'anchor_length':6,'replicate':rep,'cipher':cipher}
   streams.append(n)
  nulls.append({'replicate':rep,'seed':339099+rep,'streams':streams})
 for c in originals+[c for p in nulls for c in p['streams']]:c['public_fit_payload_sha256']=e.payload_hash(c,m)
 dump(CASES,{'session':99,'originals':originals,'null_pairs':nulls,'no_redraws':True})
 dump(SPEC,{'session':99,'plan_sha256':sha(PLAN),'driver_sha256':sha(Path(__file__)),'cases_sha256':sha(CASES),'engine_sha256':sha(e.ENGINE),'model_sha256':sha(ROOT/'first_section_model.json'),'public_fields':e.PUBLIC,'unknown_key_fits':40,'execution_order':'Null pairs0..18 stream0then1, then original stream0then1. No retries.','saved_before_any_fit':True})
 print('PREPARED 40 public payloads, original layouts and singleton coordinates',flush=True)

def verify():
 archives();spec=read(SPEC)
 for k,p in [('plan_sha256',PLAN),('driver_sha256',Path(__file__)),('cases_sha256',CASES),('engine_sha256',e.ENGINE),('model_sha256',ROOT/'first_section_model.json')]:assert spec[k]==sha(p),k

def checks():
 verify();assert not CHECKS.exists();d=read(CASES);m=model();refs,words,_=e.old.sources_and_models();pooled=f.train(refs,words)
 assert np.array_equal(m['log'],pooled['log']) and np.array_equal(m['unigram_log'],pooled['unigram_log'])
 assert len(refs)==9 and sum(map(len,refs.values()))==2977
 original=extract()
 for c,b in zip(d['originals'],original):
  for k in b:assert c[k]==b[k],k
 for pair in d['null_pairs']:
  rng=random.Random(pair['seed'])
  for c,b in zip(pair['streams'],d['originals']):
   wanted=b['cipher'].copy()
   for lo,hi in [(0,c['cut']),(c['cut'],len(wanted))]:
    ix=[i for i in range(lo,hi) if c['score_mask'][i]];vs=[wanted[i] for i in ix];rng.shuffle(vs)
    for i,v in zip(ix,vs):wanted[i]=v
   assert c['cipher']==wanted
   for k in ['starts','ends','score_mask','cut','decoder_seed']:assert c[k]==b[k]
 for c in d['originals']+[c for p in d['null_pairs'] for c in p['streams']]:
  assert e.payload_hash(c,m)==c['public_fit_payload_sha256']
  assert not set(['planted_key','gold_plaintext','constraints'])&set(e.public_case(c))
 import early_anchor_recovery_audit
 early_anchor_recovery_audit.main()
 dump(CHECKS,{'session':99,'execution_sha256':sha(SPEC),'passed':True,'model_exact_recomputation':True,'source_and_singleton_coordinates_verified':True,'payloads_checked':40,'Session98_audit_replayed':True,'new_decoder_calls':0})
 print('CHECKS PASS',flush=True)

def summarize(d,rows):
 originals=rows[-1]['streams'];nulls=rows[:-1];complete=all(s['raw']['status']=='completed' for p in rows for s in p['streams']);comparisons=[];words=[];outputs=[]
 for c,s in zip(d['originals'],originals):
  a=s['raw']
  if a['status']!='completed':continue
  output=a['prefix']['plaintext']+a['suffix']['plaintext'];outputs.append(output)
  for metric in ['prefix_mean_score','continuation_mean_score']:
   ns=[p['streams'][c['stream']]['grade'][metric] for p in nulls if p['streams'][c['stream']]['raw']['status']=='completed'];value=s['grade'][metric]
   comparisons.append({'section_id':c['section_id'],'metric':metric,'original':value,'null_maximum':max(ns) if ns else None,'margin':value-max(ns) if ns else None,'rank':1+sum(n>=value for n in ns),'null_count':len(ns),'passed':len(ns)==19 and value>max(ns)})
  for w in c['singletons']:
   value=output[w['offset']];words.append({**w,'section_id':c['section_id'],'output':value,'transliteration':LET[value],'allowed':c['constraints']['AIO_all_singletons'][str(w['offset'])],'passed':value in c['constraints']['AIO_all_singletons'][str(w['offset'])]})
  it=iter(output);literal=''.join(LET[next(it)] if ch in R else ch for ch in c['source_text']);(ROOT/f'real_pair_section{c["section_id"]}_literal.txt').write_text('FAILED/UNVERIFIED DIAGNOSTIC OUTPUT. Not a translation.\n\n'+literal+'\n')
 phrase=None if len(outputs)!=2 else outputs[0][28:34]==outputs[1][3310:3316]
 score=complete and all(c['passed'] for c in comparisons);word=len(words)==27 and all(w['passed'] for w in words if w['eligible_prior_red_exemptions'])
 return {'session':99,'complete':True,'execution_sha256':sha(SPEC),'checks_sha256':sha(CHECKS),'rows':rows,'unknown_key_fits':40,'all_fits_complete':complete,'comparisons':comparisons,'singleton_checks':words,'score_gate':score,'phrase_gate':phrase,'word_gate':word,'overall_gate':'unresolved' if not complete else 'pass' if score and phrase and word else 'fail','null_pair_anchor_agreements':sum(p['anchor_agreement'] is True for p in nulls),'no_new_plaintext':True,'branch_stopped_on_failure':complete and not(score and phrase and word)}

def run():
 verify();assert read(CHECKS)['passed'] and not RESULTS.exists();e.compile_engine();d=read(CASES);m=model();rows=[]
 pairs=[{'id':f'null{p["replicate"]:02d}','streams':p['streams']} for p in d['null_pairs']]+[{'id':'original','streams':d['originals']}]
 for p in pairs:
  streams=[]
  for c in p['streams']:
   assert e.payload_hash(c,m)==c['public_fit_payload_sha256'];answer=e.run(e.public_case(c),m);streams.append({'id':c['id'],**e.evaluate(c,answer,m,None)})
  agreement=streams[0]['grade']['anchor_output']==streams[1]['grade']['anchor_output'] if all(s['raw']['status']=='completed' for s in streams) else None
  rows.append({'id':p['id'],'streams':streams,'anchor_agreement':agreement});dump(RESULTS,{'session':99,'complete':False,'rows':rows});print('FIT',p['id'],'anchor_agreement',agreement,flush=True)
 verify();out=summarize(d,rows);dump(RESULTS,out);print('COMPLETE',out['overall_gate'],flush=True)
if __name__=='__main__':
 p=argparse.ArgumentParser();p.add_argument('stage',choices=['prepare','checks','run']);globals()[p.parse_args().stage]()
