"""Grade a committed prediction record against the released S265 gold; no model fitting.
python split_271_grade.py split_270_predictions.json display_gold_265.json display_blind_265.json split_271_results.json
"""
from collections import Counter, defaultdict
from pathlib import Path
import hashlib,json,sys
def sha(f):return hashlib.sha256(f.read_bytes()).hexdigest()
def main():
    pred,gold,blind,dest=map(Path,sys.argv[1:5])
    assert sha(pred)=='c349839bf38ab526efc1a4a9968d86fbe0bdcf3df7596828996700110ee81ebc'
    rec=json.loads(pred.read_text())['predictions'];truth={r['id']:r for r in json.loads(gold.read_text())['cases']}
    assert len(rec)==len(truth)==60 and {r['id'] for r in rec}==set(truth)
    group=defaultdict(lambda:defaultdict(Counter));byid=[]
    for row in rec:
        r=truth[row['id']];g=r['gap'];ans=r['words'][g-2:g+2];menu='in menu' if r['menu'] else 'out of menu'
        units=['overall',r['fold'],menu,r['fold']+' / '+menu,'family '+r['family'], 'base '+r['base']]
        meth={'left':row['left']['call'],'right':row['right']['call'],'pooled':row['pooled']['call'],'both':row['guess'],'both_without_top':row['guess'] if row['stable'] else None}
        ys={k:'abstain' if q is None else 'right' if q==ans else 'wrong' for k,q in meth.items()}
        for m,result in ys.items():
            for unit in units:group[unit][m][result]+=1
        byid.append(dict(id=row['id'],base=r['base'],fold=r['fold'],family=r['family'],in_menu=r['menu'],true_english=r['center_words_english'],
             data_generating_recipe=r.get('recipe'),true_four_words=ans,outcome=ys,matched_word_positions={k:[] if not v else [i for i in range(4) if v[i]==ans[i]] for k,v in meth.items()}))
    result=dict(pred_sha256=sha(pred),gold_sha256=sha(gold),counts=group,cases=byid)
    # Descriptive matched-pair check AFTER the predictions have been locked; does not select or rescore the cases.
    test={r['id']:r for r in json.loads(blind.read_text())['cases']};pidx={r['id']:r for r in rec}
    pos,neg=(next((r for r in byid if r['outcome']['both']==outcome),None) for outcome in ('right','wrong'))
    if pos and neg and pos['base']==neg['base']:
        a,b=test[pos['id']],test[neg['id']];g=a['gap'];assert g==b['gap']
        diff=[i for i,(u,v) in enumerate(zip(a['words'],b['words'])) if u!=v];assert len(a['words'])==len(b['words']) and diff==list(range(g-2,g+2))
        z=pidx[neg['id']];original=truth[neg['id']];actual=original['words'][g-2:g+2];errors=[(m-n)%29 for u,v in zip(z['guess'],actual) for m,n in zip(u,v)]
        removed={};kept={}
        for side in ('left','right'):
            q=z[side]['strongest_position'];removed[side]=[q,original['source_words_english'][q]]
            tail=z[side+'_without_top'];t=tail['strongest_position'];assert tail['min_hits']==1
            kept[side]=[t,original['source_words_english'][t]]
        result['matched_pair']=dict(good=pos['id'],bad=neg['id'],base=pos['base'],identical_exterior_positions=len(a['words'])-len(diff),
            differing_positions=diff,all_rune_errors_mod29=errors,removed_hits=removed,remaining_hits=kept)
    dest.write_text(json.dumps(result,sort_keys=True,separators=(',',':'))+'\n')
    for unit,tab in group.items():
        if unit.startswith('base '):continue
        print(unit,[(k,tuple(tab[k][s] for s in ['right','wrong','abstain'])) for k in ('left','right','pooled','both')])
    for q in byid:
        if q['outcome']['both']!='abstain':print({k:v for k,v in q.items() if k not in ('true_four_words','matched_word_positions')})
if __name__=='__main__':main()
