import pathlib,json,hashlib,csv,struct,sys
from midi_reader import parse,max_polyphony
E=pathlib.Path(sys.argv[1]) if len(sys.argv)>1 else pathlib.Path(__file__).parent
read=lambda p:json.loads(p.read_text(encoding='utf-8-sig'))
save=lambda p,x:p.write_text(json.dumps(x,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
def structure(b):
    h,fmt,tracks,ppq=struct.unpack('>IHHH',b[4:14]);p=8+h;programs=[];names=[];notechannels=set()
    for tr in range(tracks):
        assert b[p:p+4]==b'MTrk';end=p+8+int.from_bytes(b[p+4:p+8],'big');p+=8;tick=0;running=0
        def vlq():
            nonlocal p
            v=0
            while True:
                x=b[p];p+=1;v=(v<<7)|(x&127)
                if x<128:return v
        while p<end:
            tick+=vlq();st=b[p]
            if st>=128:p+=1;running=st
            else:st=running
            if st==255:
                typ=b[p];p+=1;n=vlq();v=b[p:p+n];p+=n
                if typ==3:names.append({'track':tr,'name':v.decode('utf-8',errors='replace')})
                continue
            if st in [240,247]:p+=vlq();continue
            a=b[p];p+=1
            v=0
            if st&240 not in [192,208]:v=b[p];p+=1
            if st&240==192:programs.append({'tick':tick,'track':tr,'channel':st&15,'program':a})
            if st&240==144 and v:notechannels.add(st&15)
        assert p==end
    return {'format':fmt,'tracks':tracks,'ppq':ppq,'noteChannels':sorted(notechannels),'programChanges':programs,'trackNames':names}
def score(cid,filename,runtime):
    b=(E/filename).read_bytes();m=parse(b);assert not m['danglingNotes'];ns=m['notes'];ref=read(E/('ref-'+cid+'.json'));refs=ref['notes'];used=set();pairs=[]
    for i,r in enumerate(refs):
        eligible=sorted((abs(n['start']-r['start']),j)for j,n in enumerate(ns)if j not in used and n['pitch']==r['pitch']and abs(n['start']-r['start'])<=.05)
        if eligible:
            j=eligible[0][1];used.add(j);n=ns[j];pairs.append({'referenceIndex':i,'outputIndex':j,'sourceLabelInReference':r['source'],'pitch':r['pitch'],'onsetErrorSeconds':n['start']-r['start'],'endErrorSeconds':n['start']+n['duration']-r['start']-r['duration']})
    row={'id':cid,'runtime':runtime,'download':filename,'sha256':hashlib.sha256(b).hexdigest(),'referenceAttacks':len(refs),'outputEvents':len(ns),'strictMatches':len(pairs),'missed':len(refs)-len(pairs),'extra':len(ns)-len(pairs),'maxOutputSimultaneous':max_polyphony(ns),'maxReferenceKeyHeld':max_polyphony(refs+ref['carriedInNotes']),'carriedInReferenceNotes':len(ref['carriedInNotes']),'ambiguousReferencePairs':ref['ambiguousReferencePairs'],'sourceReferenceMatches':{source:sum(x['sourceLabelInReference']==source for x in pairs)for source in sorted(set(r['source']for r in refs))},'sourceMatchCaveat':'Nearest reference association is not model instrument identification','structure':structure(b),'pairs':pairs,'danglingNotes':0}
    stem=filename[:-4]
    with (E/(stem+'-notes.csv')).open('w',newline='',encoding='utf-8')as f:
        w=csv.DictWriter(f,fieldnames=['pitch','start','duration','velocity','track','channel']);w.writeheader();w.writerows(ns)
    with (E/(stem+'-matches.csv')).open('w',newline='',encoding='utf-8')as f:
        keys=['referenceIndex','outputIndex','sourceLabelInReference','pitch','onsetErrorSeconds','endErrorSeconds'];w=csv.DictWriter(f,fieldnames=keys);w.writeheader();w.writerows(pairs)
    # An event-derived piano-roll diagram, not a DAW screenshot or listening claim.
    width,height=960,360;duration=read(E/'protocol.json')['durationSeconds'];lo=min([n['pitch']for n in ns+refs]or[21])-2;hi=max([n['pitch']for n in ns+refs]or[108])+2
    x=lambda t:70+850*t/duration;y=lambda pitch,base:base-(pitch-lo)*125/(hi-lo)
    svg=[f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" role="img" aria-label="Reference attacks and saved MIDI events for {cid}">','<rect width="960" height="360" fill="#102326"/>',f'<text x="20" y="22" fill="white" font-family="sans-serif">{cid}: source-labeled reference attacks (top), saved MIDI events (bottom)</text>']
    for sec in range(6):svg.append(f'<path d="M{x(sec)} 35 V340" stroke="#345257"/><text x="{x(sec)}" y="355" fill="#b9cfd0" font-size="12">{sec}s</text>')
    for notes,base in [(refs,160),(ns,325)]:
        for n in notes:
            color=('#68eac6'if n.get('source')=='guitar'else'#ffcb85')if base==160 else'#b7b1ff';svg.append(f'<rect x="{x(n["start"]):.3f}" y="{y(n["pitch"],base):.3f}" width="{max(1,850*n["duration"]/duration):.3f}" height="3.2" fill="{color}"/>')
    svg.append('</svg>');(E/(stem+'-piano-roll.svg')).write_text('\n'.join(svg),encoding='utf-8')
    return row
offline=[];native=[]
for c in read(E/'inputs.json')['cases']:
    for prefix,runtime in [('offline-','OFFLINE_UNMODIFIED_CURRENT_WORKER'),('baseline-','OFFLINE_ORIGINAL_SINGLE_PITCH')]:
        if (E/(prefix+c['id']+'.mid')).exists():offline.append(score(c['id'],prefix+c['id']+'.mid',runtime))
    if (E/('browser-'+c['id']+'.mid')).exists():native.append(score(c['id'],'browser-'+c['id']+'.mid','ACTUAL_PUBLIC_NATIVE_BROWSER_DOWNLOAD'))
save(E/'offline-scores.json',{'result':'INDEPENDENT_OFFLINE_SAVED_MIDI_COUNTS','scope':'Not browser conversion proof','cases':offline})
if native:save(E/'browser-scores.json',{'result':'INDEPENDENT_ACTUAL_BROWSER_SAVED_MIDI_COUNTS','cases':native})
print(json.dumps({'offline':[{k:r[k]for k in ['id','runtime','referenceAttacks','outputEvents','strictMatches','missed','extra','maxOutputSimultaneous']}for r in offline],'actualBrowserCount':len(native),'native':[{k:r[k]for k in ['id','outputEvents','strictMatches','missed','extra']}for r in native]}))
