"""Independently read back both AF1 editions, MusicXML and MIDI against the
release's three original centisecond streams, keys and source metre maps.
"""
from pathlib import Path
from fractions import Fraction as F
import json, struct, zipfile, io, tempfile, runpy
from xml.etree import ElementTree as X
from collections import defaultdict,Counter
root=Path(__file__).resolve().parent; dist=root.parent.parent; Q=384
nat=(0,2,4,5,7,9,11);tempos=[40,50,60,65,70,80,90,100,115,130,145,160,175,190,210]
def load(n):return json.loads((root/n).read_bytes())['songs']
def af1(buf):
    assert buf[:10]==b'Maestro\n\2\1'
    lengths=[]
    for p in range(10,55,5):
        assert buf[p]==64
        lengths.append(int.from_bytes(buf[p+1:p+5],'big'))
    gates=buf[55:55+lengths[0]];p=55+len(gates);voices=[]
    for le in lengths[1:]:
        voices.append(iter(struct.unpack('<'+'H'*(le//2),buf[p:p+le])));p+=le
    assert buf[p:p+4]==bytes([2,2,0,3])
    footer=buf[p:];assert len(footer)==40 and footer[-2]==6
    clocks=[F(0)]*8;carry=[{} for _ in range(8)];notes=[[] for _ in range(8)]
    tied=[False]*8;clefs=[11,11,11];sign=[0]*7;i=0;next_bar=F(0);sig=[];bars=[];key=None
    while i<len(gates):
        mask=gates[i];i+=1
        if mask==0:
            attr=gates[i];i+=1
            if attr&1:
                n=1+((attr>>1)&15);den=1<<((attr>>5)-1)
                sig.append((next_bar,n,den))
            elif attr&3==2:
                count=(attr>>3)&7;key=-count if attr&4 else count
                for letter in ((6,2,5,1,4,0,3) if key<0 else (3,0,4,1,5,2,6))[:count]:sign[letter]=-1 if key<0 else 1
            elif attr&7==4:
                clefs[attr>>6]=[11,5,3,-1][(attr>>3)&3]
            elif attr&63==32:
                # At every actual barline, all three voices terminate together.
                assert clocks[0]==clocks[1]==clocks[5]
                if attr!=96:
                    next_bar+=F(4*n,den)
                    assert clocks[0]==next_bar,(clocks[0],next_bar)
                bars.append(clocks[0]);carry=[{} for _ in range(8)]
            else:raise ValueError(attr)
            continue
        present=[c for c in range(8) if mask>>c&1]
        assert len({clocks[c] for c in present})==1
        for c in present:
            w=next(voices[c]);pos=(w>>3)&31;duration=F(8,2**(w>>13))*(2-F(1,2**((w>>11)&3)))
            a=clocks[c];b=a+duration;clocks[c]=b;p=-1
            if pos:
                step=pos+clefs[{0:0,1:1,5:2}[c]];acc=(w>>8)&7
                if acc:carry[c][pos]=[0,0,1,-1,2,-2,1,-1][acc]
                p=(step//7)*12+24+nat[step%7]+carry[c].get(pos,sign[step%7])
            if tied[c]:
                assert notes[c][-1][1:]==[a,p]
                notes[c][-1][1]=b
            else:notes[c].append([a,b,p])
            tied[c]=bool(w&4)
    assert not any(tied) and all(list(v)==[] for v in voices)
    return [[e for e in notes[c] if e[2]>=0] for c in (0,1,5)],key,sig,bars,footer

def xml_read(buf):
    tree=X.fromstring(buf);voices=[];meters=[];key=None;measures=[];trip=grace=0
    for part in tree.findall('part'):
        at=F(0);events=[];signature=[];lengths=[];pending=None
        for m in part.findall('measure'):
            before=at
            k=m.find('attributes/key/fifths')
            if k is not None:key=int(k.text)
            d=m.find('attributes/divisions')
            if d is not None:division=int(d.text)
            time=m.find('attributes/time')
            if time is not None:signature.append((at,int(time.findtext('beats')),int(time.findtext('beat-type'))))
            for n in m.findall('note'):
                pitch=n.find('pitch');sounding=pitch is not None
                if sounding:
                    p=(int(pitch.findtext('octave'))+1)*12+nat['CDEFGAB'.index(pitch.findtext('step'))]+int(pitch.findtext('alter','0'))
                if n.find('grace') is not None:
                    frac=F(n.find('grace').get('steal-time-previous'))/100
                    old=events[-1]; when=at-(at-old[0])*frac
                    old[1]=when;events.append([when,at,p]);grace+=1;continue
                dur=F(int(n.findtext('duration')),division)
                typ=n.findtext('type')
                if typ:
                    kinds=['breve','whole','half','quarter','eighth','16th','32nd','64th']
                    val=F(8,2**kinds.index(typ))*(2-F(1,2**len(n.findall('dot'))))
                    tu=n.find('time-modification')
                    if tu is not None:val*=F(int(tu.findtext('normal-notes')),int(tu.findtext('actual-notes')));trip+=1
                    assert dur==val,(dur,val)
                if sounding:
                    stop=n.find('tie[@type="stop"]') is not None;start=n.find('tie[@type="start"]') is not None
                    if stop:
                        assert pending==p and events[-1][1]==at;events[-1][1]=at+dur
                    else:
                        assert pending is None;events.append([at,at+dur,p])
                    pending=p if start else None
                at+=dur
            lengths.append(at-before)
        if voices:assert meters==signature and lengths==measures
        else:meters=signature;measures=lengths
        assert pending is None
        voices.append(events)
    return voices,key,meters,measures,trip,grace

def midi_read(buf):
    assert buf[:4]==b'MThd'
    fmt,n,d=struct.unpack_from('>HHH',buf,8);assert (fmt,n)==(1,4)
    off=14;parts=[];ends=[];maps=[];tempo=[];key=None
    for j in range(4):
        assert buf[off:off+4]==b'MTrk';end=off+8+int.from_bytes(buf[off+4:off+8],'big');off+=8
        t=0;active={};events=[]
        def vlq():
            nonlocal off
            x=0
            while True:
                v=buf[off];off+=1;x=x*128+(v&127)
                if v<128:return x
        while off<end:
            t+=vlq();status=buf[off];off+=1
            if status==255:
                k=buf[off];off+=1;ln=vlq();data=buf[off:off+ln];off+=ln
                if k==81:tempo.append((t,int.from_bytes(data,'big')))
                if k==88:maps.append((F(t,d),data[0],2**data[1]))
                if k==89:key=int.from_bytes(data[:1],'big',signed=True)
                if k==47:ends.append(F(t,d))
            elif status>>4 in (8,9):
                p,v=buf[off:off+2];off+=2
                if status>>4==9:assert p not in active;active[p]=F(t,d)
                else:events.append([active.pop(p),F(t,d),p])
            else:raise ValueError(status)
        assert not active
        if j:parts.append(events)
    assert off==len(buf) and len(set(ends))==1 and len(tempo)==1
    return parts,key,maps,tempo[0][1],ends[0]

def run():
    tracks=load('TrackerInput');scores=load('MusicData');ks=load('MusicKeys');picks=load('RhythmSources')
    total=0;max_native=0;tempmatch=0;rows=[]
    holy=json.loads((root/'HolySix').read_text())
    with zipfile.ZipFile(dist/'Docs/OpenScores') as z:
        for i,(t,s,k,r) in enumerate(zip(tracks,scores,ks,picks),1):
            name=next(p.name for p in (dist/'Maestros').glob(f'{i:02}-*'))
            data,key,sig,bar,footer=af1((dist/'Maestros'/name).read_bytes())
            alt,key2,sig2,bar2,f2=af1((dist/'MaestrosPluck'/name).read_bytes())
            assert (data,key,sig,bar)==(alt,key2,sig2,bar2)
            assert list(footer[5:20:2])==[1]*8 and list(f2[4:20:2])==list(range(8))
            assert list(f2[5:20:2])==[3,2,2,2,2,2,2,2]
            assert f2[20]==4 and list(f2[21:29])==[6]*8 and footer[29:]==f2[29:]
            xv,xk,xm,xl,tuplet,grace=xml_read(z.read('MusicXML/'+name+'.musicxml'))
            mv,mk,mm,us,tail=midi_read(z.read('MIDI/'+name+'.mid'))
            assert key==xk==mk==k['keys'][0][1]
            assert len(xv)==len(mv)==3
            maps=[(F(at,t['division']),n,d) for at,n,d in t['meters']]
            if i==1:maps=[(F(0),6,8)]
            if i==25:maps=[(F(0),6,8)]
            assert xm==mm==maps,(i,xm,mm,maps)
            target_usec=555556 if i==25 else t['tempo'][0][1]*(2 if i==1 else 1)
            assert us==target_usec
            loopcs=round(F(228*us,10000))+200 if i==25 else s['duration_cs']
            assert round(tail*us/10000)==loopcs
            pickup=F(0) if i==25 else F(str(r['pickup_beats']));n,d=maps[0][1:];pad=F(4*n,d)-pickup if pickup else 0
            assert not pickup or xl[0]==pickup
            native_maps=[(0 if at==0 else at+pad,n,d) for at,n,d in maps]
            if i==29:native_maps=sorted(native_maps+[(44+pad,1,8),(F('44.5')+pad,6,8)])
            assert sig==native_maps,(i,sig,native_maps)
            elapsed=F(0)
            for le,barpos in zip(xl,bar):
                elapsed+=le
                assert barpos==elapsed+pad,(i,barpos,elapsed,pad)
            assert len(bar)==len(xl)
            assert tuplet==(6 if i==30 else 0) and grace==0
            maxdiff=F(0)
            if i==25:
                tree=X.fromstring(z.read('MusicXML/'+name+'.musicxml'))
                parts=tree.findall('part')
                assert [p.findtext('measure/attributes/clef/sign') for p in parts]==['G','G','F']
                assert len(xl)==76 and xl==[3]*76 and key==-5 and footer[-1]==tempos.index(115)
                assert parts[0].findtext('measure/direction/direction-type/metronome/per-minute')=='72'
                assert len(parts[0].findall('.//lyric'))==125
                assert [p for a,b,p in xv[0]]==[p for a,b,p in s['streams'][0] if p>=0]
                assert xv[0][:4]==[[3,F(9,2),65],[F(9,2),F(11,2),65],[F(11,2),6,65],[6,F(15,2),68]]
                assert [p for a,b,p in xv[1][:6]]==[53,61,56,65,61,56]
                assert xv[2][0]==[0,6,37] and [v[-1][-1]%12 for v in xv]==[1,1,1]
                for staff,(voice,xmlnotes,midnotes,natives) in enumerate(zip(('voice','right','left'),xv,mv,data)):
                    exact_notes=[[F(a,4),F(b,4),p] for a,b,p in holy[voice] if p>=0]
                    assert exact_notes==xmlnotes==midnotes==natives
                    total+=len(exact_notes)
                rows.append((s['title'],0,115,float(60000000/us),0))
                continue
            for v,xx,mm0,nn in zip(s['streams'],xv,mv,data):
                original=[(a,b,p) for a,b,p in v if p>=0]
                assert len(xx)==len(mm0)==len(nn)==len(original)
                for e,x,m,na in zip(original,xx,mm0,nn):
                    a,b,p=e
                    assert x[2]==m[2]==na[2]==p
                    for idx,cents in enumerate((a,b)):
                        assert round(x[idx]*us/10000)==round(m[idx]*us/10000)==cents,(i,e,x,m)
                        assert abs(x[idx]-m[idx])<F(1,10**7)
                        delta=abs(na[idx]-pad-m[idx]);maxdiff=max(delta,maxdiff)
                total+=len(original)
            bound={30:F(1,24)}.get(i,0)
            assert maxdiff<=bound,(i,maxdiff,bound)
            ms=float(maxdiff*us/1000);max_native=max(max_native,ms)
            native=tempos[footer[-1]];tempmatch+=(abs(native-60000000/us)<.001)
            rows.append((s['title'],ms,native,float(60000000/us),float(pad)))
    print(f'{len(rows)} scores / 92 Maestro files; {total} pitched attacks verified in both native sets, MusicXML and MIDI.')
    print(f'Native beat placement: 45 exact to their respective editions; Wexford {rows[29][1]:.3f} ms maximum.')
    print(f'{tempmatch} of 46 source tempos match a native preset to 0.001 BPM. 45 MIDI files match the existing app centiseconds. The O Holy Night MIDI follows the new 6/8 edition exactly.')
    return rows
if __name__=='__main__':run()
