"""Verify continuous percussion from the native MOD bytes, not arrangement labels."""
from pathlib import Path
import hashlib
import json
import struct
import numpy as np

root=Path(__file__).resolve().parent
tracker=root.parent.parent/'!Xmas26/Tracker'
tracks=json.loads((root/'TrackerModes').read_text())['tracks']
src=json.loads((root/'TrackerInput').read_text())['songs']
pickups=json.loads((root/'RhythmSources').read_text())['songs']
samples={s['name']:s for s in json.loads((root/'TranceSrc').read_text())['samples']}
index=(tracker/'Index').read_bytes()
assert struct.unpack_from('<4sIII',index)==(b'X26I',1,43,4)
assert len(index)==16+43*4*12
totals={2:0,4:0}
trance_samples=set()
for m in tracks:
    style=m['style']
    if style not in (2,4):continue
    i=m['song']; size=m['rows']
    folder='Dance' if style==2 else 'Trance'
    mod=(tracker/folder/f"C{i+1:02}").read_bytes()
    timing=(tracker/folder/f"M{i+1:02}").read_bytes()
    assert struct.unpack_from('<4s4I',timing)==(b'X26R',1,size,style,i)
    assert struct.unpack_from('<III',index,16+((style-1)*43+i)*12)==(m['duration_cs'],size,m['tempo'])
    data=np.frombuffer(mod[1084:1084+size*32],dtype='u1').reshape(size,8,4)
    kicks=(data[:,5,0]&240)|(data[:,5,2]>>4)
    where=np.flatnonzero(kicks)
    assert len(where)>0 and where[0]==0
    name='Pop Punch Kick' if style==2 else 'Vector Kick'
    sid=next(j+1 for j in range(31) if mod[20+j*30:42+j*30].split(b'\0')[0]==name.encode())
    assert (kicks[where]==sid).all()
    assert np.all(((data[where,5,0]&15)!=0)|(data[where,5,1]!=0))
    assert np.all((data[where,5,2]&15!=12)|(data[where,5,3]>=25))
    if style==4:
        n,d=(src[i].get('meters') or [[0,4,4]])[0][1:]
        pulse=36 if d==8 and n%3==0 else 24
        anchor=m['intro_rows']+round(pickups[i]['pickup_beats']*24)
        expected={0,*range(anchor%pulse,size-1,pulse)}
        assert set(where)==expected and 144 <= m['tempo']*24/pulse <= 156
        assert len(m['tempo_changes'])==1
        offset=1084+size*32
        for k in range(31):
            length=struct.unpack_from('>H',mod,42+k*30)[0]*2
            if not length:continue
            instrument=mod[20+k*30:42+k*30].split(b'\0')[0].decode()
            digest=hashlib.sha256(mod[offset:offset+length]).hexdigest()
            assert digest==samples[instrument]['sha256'] and length==samples[instrument]['size_bytes']
            offset+=length;trance_samples.add(instrument)
        assert offset==len(mod)
    else:
        # The maximum local pulse is one dotted crotchet (36 rows).
        # Each expected pulse, including partial pickup and final measure, must sound.
        def period(bar):
            n,d=bar['meter']
            return 36 if d==8 and n%3==0 else min(24,round(96/d))
        intro=m['intro_rows']; body=intro+m['body_rows']
        expected=set(range(0,intro,period(m['bars'][0])))
        for bar in m['bars']:
            expected.update(range(intro+bar['start'],min(size-1,intro+bar['end']),period(bar)))
        expected.update(range(body,size-1,period(m['bars'][-1])))
        assert set(where)==expected,(m['title'],sorted(expected^set(where)))
    assert np.diff(np.append(where,size-1)).max()<=36
    totals[style]+=len(where)
assert totals[2]>0 and totals[4]>0 and trance_samples==set(samples)
print('Verified 43 PC-Pop and 43 Dance/Trance modules:',totals,'kick attacks; every pulse through the final bar, and all',len(samples),'original trance sample hashes.')
