"""Score Session 267 and run Session 274's independent-rune veto. stdlib.
python -B probe_274.py [inputs_dir] [output_file]
Input directory contains the published blind, gold, and prediction JSONs.
"""
from pathlib import Path
from collections import defaultdict,Counter
from math import comb
from fractions import Fraction
from itertools import combinations
import sys,json,hashlib
def read(p,h):
 b=p.read_bytes();assert hashlib.sha256(b).hexdigest()==h,p
 rows=json.loads(b)['cases']; out={r['id']:r for r in rows};assert len(out)==len(rows)==60
 return out
def rat(n,d,k):
 assert 0<=d<=n and 1<=k<=n
 return Fraction(comb(n-d,k),comb(n,k))
def probes(words):return [words[2][0],words[1][-1],words[0][0],words[3][-1]]
assert probes([[0,1],[2,3],[4,5],[6,7]])==[4,3,0,7]
for k in (1,2,4):
 for d in range(6):
  assert rat(5,d,k)==Fraction(sum(all(i>=d for i in pick) for pick in combinations(range(5),k)),comb(5,k))
def main(src,out):
 b=read(src/'display_blind_265.json','22213465388ba14a0a7d350baf3f381ce4058952d585bd34d7ffaaf2332d5ed3')
 g=read(src/'display_gold_265.json','93c08138eae9044bd7c41312d582f1c4e76a96c6b1d1b1e712e1c48d3caeaacc')
 p=read(src/'display_predictions_266.json','aab5dd56639da01cc908b8eeffe06f130941d14f1530c62940f1aee0103f9334')
 assert b.keys()==g.keys()==p.keys()
 rows=[]; twins={}
 for i in sorted(b):
  y=g[i];q=p[i];gap=y['gap'];w=y['words'][gap-2:gap+2];a=q['guess'];right=(a==w)
  assert b[i]['gap']==gap and b[i]['fold']==q['fold']==y['fold']
  assert (a is not None)==q['is_consensus'] and (a is not None or not q['is_support'])
  assert a is None or list(map(len,a))==list(map(len,w))
  n=sum(map(len,w));d=None if a is None else sum(aa!=gg for aw,gw in zip(a,w) for aa,gg in zip(aw,gw))
  survived=None if a is None else [j==v for j,v in zip(probes(a),probes(w))]
  assert not right or all(survived)
  rows.append(dict(id=i,fold=y['fold'],base=y['base'],family=y['family'],menu=y['menu'],outcome='none' if a is None else 'right' if right else 'wrong',support=q['is_support'],L=n,D=d,probes_match=survived))
  if y['family'] in ('menu','switch'):twins.setdefault(y['base'],{})[y['family']]=b[i]
 comparisons=[]
 for name,v in sorted(twins.items()):
  a,z=v['menu'],v['switch'];t=a['gap'];ms=a['words'];ss=z['words']
  sameout=ms[:t-2]+ms[t+2:]==ss[:t-2]+ss[t+2:];sameall=ms==ss
  assert t==z['gap'] and sameout and not sameall and all(c!=e for cw,ew in zip(ms[t-2:t+2],ss[t-2:t+2]) for c,e in zip(cw,ew))
  comparisons.append(dict(base=name,menu=a['id'],switch=z['id'],same_outside=sameout,same_whole=sameall))
 def tally(rr,gate):
  c=Counter(r['outcome'] if gate(r) else 'none' for r in rr)
  return {k:c[k] for k in ['right','wrong','none']}
 summary={}
 for fold in ['calibration','evaluation']:
  rr=[r for r in rows if r['fold']==fold];wrong=[r for r in rr if r['outcome']=='wrong']
  groups={'all':rr}
  for key in ['base','family','menu']:
   for value in sorted(set(r[key] for r in rr)):groups[f'{key}:{value}']=[r for r in rr if r[key]==value]
  scores={label:{'consensus':tally(gg,lambda r:True),'support':tally(gg,lambda r:r['support'])} for label,gg in groups.items()}
  fixed=[tally(rr,lambda r:r['probes_match'] is not None and all(r['probes_match'][:k])) for k in range(5)]
  exp={str(k):sum((rat(r['L'],r['D'],k) for r in wrong),Fraction(0)) for k in [1,2,4]}
  summary[fold]=dict(raw=scores,fixed_veto=fixed,random_expected_wrong={k:[v.numerator,v.denominator] for k,v in exp.items()})
 out.write_text(json.dumps(dict(measures='right=all four words exactly correct; none=original abstention or veto; selectivity reported per case',summary=summary,rows=rows,twins=comparisons),sort_keys=True,separators=(',',':'))+'\n')
if __name__=='__main__':
 main(Path(sys.argv[1]) if len(sys.argv)>1 else Path('.'),Path(sys.argv[2]) if len(sys.argv)>2 else Path('probe_274_results.json'))
