#!/usr/bin/env python3
"""Independent standard-library calculation of order bounds; no learned weights."""
import json,itertools,hashlib
from pathlib import Path
ROOT=Path(__file__).resolve().parent
ORDER={'purpose':['decide','explore'],'evidence':['absent','cited','checked'],'currency':['old','current'],'coverage':['partial','complete'],'conflict':['unresolved','clear'],'attestation':['absent','present']}
LABELS=['reject','ask','accept']
def le(a,b):return all(values.index(a[k])<=values.index(b[k]) for k,values in ORDER.items())
def bound(x,h):
 return max([LABELS.index(c['truth']) for c in h if le(c['x'],x)]+[0]),min([LABELS.index(c['truth']) for c in h if le(x,c['x'])]+[2])
def calculate(data):
 lookup={c['id']:c for c in data['cases']};out={}
 for phase in ['same','changed','corrected','retained']:
  rows=[]
  for split in data['splits']:
   after=phase in ['corrected','retained'];h=[lookup[k] for k in split['initial']+(split['correction'] if after else [])]
   assert all(LABELS.index(a['truth'])<=LABELS.index(b['truth']) for a in h for b in h if le(a['x'],b['x']))
   use='explore' if phase in ['same','retained'] else 'decide'
   for k in split['test_'+use]:
    c=lookup[k];a,b=bound(c['x'],h);assert a<=LABELS.index(c['truth'])<=b;rows.append({'id':k,'lo':a,'hi':b})
  out[phase]={'n':len(rows),'identified':sum(x['lo']==x['hi'] for x in rows),'rows':rows}
 return out
if __name__=='__main__':
 d=json.loads((ROOT/'data.json').read_text());r=calculate(d);(ROOT/'results.json').write_text(json.dumps(r,indent=2)+'\n');print({k:{z:v[z] for z in ['n','identified']} for k,v in r.items()})
