import pathlib,json,hashlib,sys
from midi_reader import parse
E=pathlib.Path(__file__).parent
def sha(b):return hashlib.sha256(b).hexdigest()
rows=[]
for cid in ['guitar','piano','mix','offset-mix']:
    p=E/('browser-'+cid+'.mid')
    if not p.exists():continue
    a=p.read_bytes();b=(E/('offline-'+cid+'.mid')).read_bytes();pa,pb=parse(a),parse(b)
    diffs=[]
    if len(pa['notes'])==len(pb['notes']):
        for i,(left,right)in enumerate(zip(pa['notes'],pb['notes'])):
            for key in sorted(set(left)|set(right)):
                if left.get(key)!=right.get(key):diffs.append({'noteIndex':i,'field':key,'browser':left.get(key),'offline':right.get(key)})
    row={'id':cid,'browserSha256':sha(a),'offlineSha256':sha(b),'bytesEqual':a==b,'byteLengths':[len(a),len(b)],'differentByteOffsets':[i for i in range(min(len(a),len(b)))if a[i]!=b[i]][:200],'noteCounts':[len(pa['notes']),len(pb['notes'])],'noteDifferences':diffs,'parsedStructureEqual':{key:pa[key]==pb[key]for key in ['format','tracks','ppq','tempos','controls','danglingNotes']},'scope':'Explicit runtime comparison; different hashes never reported as identical, no new tolerance and no inferred cause'}
    row['pitchTimingDurationIdentical']=len(pa['notes'])==len(pb['notes'])and not any(x['field']in ['pitch','start','duration','track','channel']for x in diffs)
    rows.append(row)
out={'result':'MEASURED_CROSS_RUNTIME_DIFFERENCES_NOT_BYTE_EQUIVALENCE_PASS','cases':rows,'cause':'Not established; no browser decode/model/rounding cause inferred from these comparisons alone','reproductionPolicy':'Fresh offline-directory reproduction remains exact26files; actual browser outputs are primary for the page. Preserve and independently score each runtime; do not relax exact pitch/onset matching or assert all browser/Node hashes agree.'}
(E/'runtime-comparison.json').write_text(json.dumps(out,indent=2)+'\n',encoding='utf-8')
print(json.dumps(out))
