"""Recheck saved MIDI scores; keep this beside the downloaded proof files."""
import json,pathlib,hashlib
from midi_reader import parse
E=pathlib.Path(__file__).parent
r=json.loads((E/'native-retest.json').read_text(encoding='utf-8-sig'));out=[]
for c in r['cases']:
 b=(E/c['download']).read_bytes();assert hashlib.sha256(b).hexdigest()==c['downloadSha256'];m=parse(b);ns=m['notes'];assert not m['danglingNotes'];refpath=E/('ref-'+c['id'].rsplit('-',1)[0]+'.json');refs=json.loads(refpath.read_text(encoding='utf-8'))['notes'];used=set();matched=0
 for ref in refs:
  eligible=sorted((abs(n['start']-ref['start']),j)for j,n in enumerate(ns)if j not in used and n['pitch']==ref['pitch']and abs(n['start']-ref['start'])<=.05)
  if eligible:used.add(eligible[0][1]);matched+=1
 row={'id':c['id'],'referenceAttacks':len(refs),'outputEvents':len(ns),'strictMatches':matched,'missed':len(refs)-matched,'extra':len(ns)-matched}
 assert all(row[k]==c[k]for k in row);out.append(row)
print(json.dumps({'result':'PASS_SAVED_MIDI_COUNTS','matching':'exact pitch, onset<=50ms, reference-order nearest-unused; no shift/octave credit','cases':out},indent=2))
