"""Independent native-MOD beat checks for the v2.26 chillout and pop sets."""
from pathlib import Path
import json,struct,numpy as np
r=Path(__file__).resolve().parent;tracks=json.loads((r/'TrackerModes').read_text())['tracks'];sources=json.loads((r/'TrackerInput').read_text())['songs'];rhythm=json.loads((r/'RhythmSources').read_text())['songs'];total=0
for t in tracks[:86]:
 index=t['song'];style=t['style'];source=sources[index];folder=('Chill','Dance')[style-1]
 raw=(r.parent.parent/'!Xmas26/Tracker'/folder/f'C{index+1:02}').read_bytes()
 rows=np.frombuffer(raw[1084:1084+t['rows']*32],dtype='u1').reshape(-1,8,4)
 sid=(rows[:,:,0]&240)|(rows[:,:,2]>>4)
 def sample_name(n):return raw[20+(n-1)*30:42+(n-1)*30].split(b'\0')[0].decode()
 primary=[n['start_row'] for n in t['primary']]
 assert {sample_name(int(sid[i,0])) for i in primary}=={t['lead_instrument']}
 assert t['arrangement']==[['Balearic house','Deep house','Downtempo breaks','Melodic house'],['Dance pop','Synth pop','Tropical pop','Future pop']][style-1][index%4]
 cursor=0
 for b in t['bars']:
  assert b['start']==cursor;cursor=b['end'];assert b['end']>b['start']
  n,d=b['meter'];assert b['length']==round(n*96/d)
  assert b['pulse']==(36 if d==8 and n%3==0 else round(96/d))
  if b['pickup']:assert b['start']==0 and b['end']==round(rhythm[index]['pickup_beats']*24)
 for hit in t['rhythm']:
  b=t['bars'][hit['bar']];off=hit['row']-t['intro_rows']-b['start']
  assert 0<=off<b['end']-b['start']
  if hit['kind'] in ('kick','snare'):
   step=24 if style==2 and b['pulse']>36 else b['pulse']
   assert off%step==0 and (style==2 or not b['pickup']),(t['title'],hit,'off-beat strong accent')
   ch=5 if hit['kind']=='kick' else 6
   assert sid[hit['row'],ch]>0,(t['title'],'missing native drum hit')
  total+=1
 assert all(s['row']-t['intro_rows'] in t['phrase_rows'] for s in t['sections'])
 # Silent Night retains genuine 3/4, no 4:3 remapping or drifting four-beat bar.
 if index==0:
  assert all(b['length']==72 and b['pulse']==24 for b in t['bars'])
  assert [n['start_row']-t['intro_rows'] for n in t['primary'][:4]]==[0,36,48,72]
 # Noel's opening two quavers are a pickup, not a downbeat.
 if index==9:assert t['bars'][0]['end']==24 and t['bars'][1]['start']==24
print(f'PASS: {total} native percussion positions; 86 stable leads; alternating style families; score metres, pickup bars, phrase boundaries, Silent Night 3/4 and Noel pickup')
