"""Read back song 39 from the actual deliverables; assert every melody attack."""
from pathlib import Path
import json, math, runpy, struct, zipfile
from fractions import Fraction
root=Path(__file__).resolve().parent;dist=root.parent.parent
read=lambda n:json.loads((root/n).read_text())
# Independent reference in A-flat. Each space separates one bar of the vocal line.
verse='63,72,70,68 63,63,63 63,72,70,68 65 65,73,72,70 67 75,75,73,70 72 63,72,70,68 63 63,72,70,68 65 65,73,72,70 75,75,75,75 77,75,73,70 68'
common='72,72,72 72,72,72 72,75,68,70 72 73,73,73,73 73,72,72,72,72'
ch1=common+' 72,70,70,72 70,75';ch2=common+' 75,75,73,70 68'
unpack_notes=lambda s:[int(w) for w in s.replace(',',' ').split()]
want=unpack_notes(verse+' '+ch1+' '+ch2);chorus=unpack_notes(ch1+' '+ch2)
def event(e):
    a,b,c,d=e
    return (a&16)|(c>>4),((a&15)<<8)|b
def midi_pitch(period,base,ref):
    return round(base+12*math.log2(ref/period))
def pitches(data,rows,bank,sids,channel=0):
    out=[]
    for row in range(rows):
        at=(row*8+channel)*4;sid,p=event(data[at:at+4])
        if sid and p:
            s=bank[sids[sid-1]];out.append((row,midi_pitch(p,s['base'],s['period'])))
    return out
song=read('MusicData')['songs'][38];traditional=(dist/'!Xmas26/Carols').read_bytes()
seq=[struct.unpack_from('<iii',traditional,16+(song['bases'][0]+i)*12) for i in range(song['counts'][0])]
lead=[(a,b,round(60+(p-16384)*12/4096)) for a,b,p in seq if p>=0]
assert [p for a,b,p in lead]==want
cues=read('LyricInput')['songs'][38]['cues']; onset={a for a,b,p in lead}
assert all(a in onset for a,_ in cues) and len(lead)==len(cues)+1
# Read source and destination line records used by the karaoke screens.
ly=(dist/'!Xmas26/Lyrics').read_bytes();nt=struct.unpack_from('<I',ly,8)[0]
first,count=struct.unpack_from('<II',ly,12+38*8);data=12+nt*8+first*80
assert [struct.unpack_from('<I',ly,data+r*80)[0] for r in range(count)]==[a for a,_ in cues]
samples=runpy.run_path(str(root/'BuildTrackers'))['samples'](root)
bank={s['name']:s for s in samples+read('ClubSources')['samples']+read('TranceSrc')['samples']}
tracker=dist/'!Xmas26/Tracker'
for t in [t for t in read('TrackerModes')['tracks'] if t['song']==38]:
    b=(tracker/('Chill','Dance','Class','Trance')[t['style']-1]/'C39').read_bytes()
    names=[b[20+i*30:42+i*30].split(b'\0')[0].decode() for i in range(31)]
    got=dict(pitches(b[1084:],t['rows'],bank,names))
    attacks=[n for n in t['primary'] if n['channel']==0]
    assert [got[n['start_row']] for n in attacks]==want
    assert [n['source_start_cs'] for n in attacks]==[a for a,b,p in lead]
kit=(tracker/'Mix/DJDeck').read_bytes()
names=[kit[20+i*30:42+i*30].split(b'\0')[0].decode() for i in range(31)]
deck=(tracker/'Mix/J39').read_bytes(); rows=struct.unpack_from('<I',deck,28)[0]
assert [p for _,p in pitches(deck[36:],rows,bank,names)]==want
decode=runpy.run_path(str(root/'CheckScores'))
for folder in ('Maestros','MaestrosPluck'):
    data=decode['af1']((dist/folder/'39-Jingle-Bells').read_bytes())
    assert [p for _,_,p in data[0][0]]==want and data[1]==-4
with zipfile.ZipFile(dist/'Docs/OpenScores') as z:
    for ext,folder,func in [('mid','MIDI','midi_read'),('musicxml','MusicXML','xml_read')]:
        data=decode[func](z.read(f'{folder}/39-Jingle-Bells.{ext}'))
        assert [p for _,_,p in data[0][0]]==want and data[1]==-4
med=read('TrackerData');start=next(s['row'] for s in med['sections'] if s['title']=='Jingle Bells - chorus')
mod=(tracker/'NeonMOD').read_bytes();actual=[]
for r in range(start,start+256):
    at=1084+((mod[952+r//64]*64+r%64)*8+4)*4
    sid,p=event(mod[at:at+4])
    if p:actual.append((r-start,midi_pitch(p,med['samples'][sid-1]['base_midi'],3546894.6/8363)))
assert [p for _,p in actual]==[p+4 for p in chorus]
dtt=(tracker/'NeonDTT').read_bytes();n=struct.unpack_from('<I',dtt,140)[0];os=168+((n+3)//4*4)
offsets=struct.unpack_from('<'+'I'*n,dtt,os);other=[]
for pat in range(start//64,(start+255)//64+1):
    pos=offsets[pat]
    for r in range(64):
        for ch in range(8):
            w=struct.unpack_from('<I',dtt,pos)[0];pos+=8 if w&(31<<17) else 4
            note=(w>>6)&63;row=pat*64+r
            if ch==4 and note and start<=row<start+256:other.append((row-start,note+35))
assert other==actual
print(f'Passed: {len(want)} lead attacks in Traditional, four tracker genres, the DJ deck, two Maestro scores, MIDI and MusicXML; both medley encodings agree on all {len(chorus)} chorus notes.')
