#!/usr/bin/env python3
from pathlib import Path
import argparse,json,math
from fractions import Fraction
from collections import Counter,defaultdict
def main():
 a=argparse.ArgumentParser();a.add_argument('pred',type=Path);a.add_argument('gold',type=Path);a.add_argument('output',type=Path);x=a.parse_args()
 p=json.loads(x.pred.read_bytes())['cases'];g={r['id']:r for r in json.loads(x.gold.read_bytes())['cases']}
 assert len(g)==len(p)==60 and len({z['id'] for z in p})==60
 counts=defaultdict(Counter);stats=defaultdict(Counter);details=[];rand=defaultdict(Fraction)
 for r in p:
  t=g[r['id']];f=t['fold'];assert r['fold']==f
  w=t['words'][t['gap']-2:t['gap']+2];hat=r['guess_words'];fam=t['family'];L=sum(map(len,w))
  if hat is None:assert not r['is_consensus'] and not r['is_support']
  else:assert r['is_consensus'] and list(map(len,w))==list(map(len,hat)) and len(w)==4
  ok=hat==w
  for typ,pick in [('consensus',r['is_consensus']),('support',r['is_support'])]:
   tag='right' if pick and ok else 'wrong' if pick else 'null'
   for key in [(f,typ,'all'),(f,typ,fam)]:stats[key][tag]+=1
  probes=[(2,0),(1,-1),(0,0),(3,-1)]
  flags=[hat is not None and hat[i][j]==w[i][j] for i,j in probes]
  for k in range(5):
   active=hat is not None and all(flags[:k])
   counts[f,k]['right' if active and ok else 'wrong' if active else 'null']+=1
  if hat is not None:
   d=sum(a!=b for pw,tw in zip(hat,w) for a,b in zip(pw,tw))
   assert ok==(d==0)
   q={k:Fraction(math.comb(L-d,k),math.comb(L,k)) for k in [1,2,4]}
   if not ok and f=='evaluation':
    for k,v in q.items():rand[k]+=v
   details.append(dict(id=t['id'],fold=f,family=fam,correct=ok,L=L,D=d,matching_probe_sequence=flags,random_survival={k:str(v) for k,v in q.items()}))
 plain=lambda c:dict(right=c['right'],wrong=c['wrong'],null=c['null'])
 out={'raw':{f:{a:{b:plain(stats[f,a,b]) for b in ('all','menu','near','other','switch','noise')} for a in ('consensus','support')} for f in ['calibration','evaluation']},
      'veto':{f:{k:plain(counts[f,k]) for k in range(5)} for f in ('calibration','evaluation')},'wrong_eval_random_expected_counts':{k:str(v) for k,v in rand.items()},'raw23':details}
 x.output.write_text(json.dumps(out,indent=1)+'\n')
 print('veto',out['veto']);print('raw',out['raw']);print('random eval',[(k,str(v),float(v)) for k,v in rand.items()])
 print('eval wrong survival',[(v['family'],v['L'],v['D'],v['random_survival']) for v in details if v['fold']=='evaluation' and not v['correct']])
if __name__=='__main__':main()
