"""Score verified LD ablations at frozen four-field and exact-core endpoints."""
import hashlib,json
from pathlib import Path
from endpoints import named_pair,unmatched_cores
B=Path(__file__).resolve().parent
sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
load=lambda p:json.loads(p.read_text())
def main():
 plan=load(B/'SCORE_PLAN.json')
 for n,h in plan['inputs_sha256'].items():assert sha(B/n)==h
 assert sha(B/'PLAN.json')==plan['inference_plan_sha256']
 truth=load(B/'TRUTH.json');proof=load(B/'COLLECTION.json');rows=[]
 for entry in proof['verified']:
  arm=entry['arm'];out=B/'collected'/arm['donor']/arm['panel'];assert sha(out/'RESULT.json')==entry['result_sha256'];receipt=load(out/'RESULT.json')
  for mode in ['independent','linked','shuffled']:
   assert sha(out/(mode+'.json'))==receipt['output_sha256'][mode+'.json'];calls=load(out/(mode+'.json'))['calls']
   for gene,copies in truth[arm['donor']].items():
    c=calls[gene];rows.append({'donor':arm['donor'],'panel':arm['panel'],'mode':mode,'gene':gene,'numeric_four_field':named_pair(c['slots'],copies),'unmatched_core':unmatched_cores(c['slots'],copies),'assigned_fragments':c['assigned_fragments'],'imputed_without_assigned_reads':c['imputed_without_assigned_reads']})
 totals=[]
 for panel,mode in sorted({(r['panel'],r['mode']) for r in rows}):
  for scope in ['all_loci','loci_with_assigned_reads']:
   rr=[r for r in rows if r['panel']==panel and r['mode']==mode and (scope=='all_loci' or not r['imputed_without_assigned_reads'])]
   totals.append({'panel':panel,'mode':mode,'scope':scope,'donors':len({r['donor'] for r in rr}),'eligible_pairs':sum(r['numeric_four_field']['eligible'] for r in rr),'correct_pairs':sum(r['numeric_four_field']['correct'] for r in rr),'unmatched_copies':sum(r['unmatched_core']['eligible_copies'] for r in rr),'unmatched_recovered':sum(r['unmatched_core']['exact_copies_recovered'] for r in rr)})
 result={'status':'complete' if len(proof['verified'])==proof['planned'] else 'partial','score_plan_sha256':sha(B/'SCORE_PLAN.json'),'collection_sha256':sha(B/'COLLECTION.json'),'rows':rows,'totals':totals,'phase_accuracy_assessed':False,'limitations':['Previously exposed pilot; these conditional read-likelihood ablations do not replace the primary native/hybrid benchmarks.','Interpret linked versus independent and shuffled comparisons within identical panels and completed donors.','Unphased four-field and exact core endpoints; no within-gene block or chromosome-phase claim.','Posterior calibration unestablished.']}
 (B/'SCORES.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps({'status':result['status'],'totals':totals}))
if __name__=='__main__':main()
