"""Validate 2.50 melodic variants and decode all newly changed MOD rows.
Optional --render uses the independent libopenmpt decoder for full playback.
"""
from pathlib import Path
import json,struct,runpy,argparse,ctypes,ctypes.util,math
ROOT=Path(__file__).resolve().parent;DIST=ROOT.parent.parent
read=lambda n:json.loads((ROOT/n).read_text())
songs=read('MusicData')['songs'];tr=read('TrackerInput')['songs'];review=read('TwelveReview');t=tr[22];q=t['division'];lead=t['tracks'][0]['notes']
for verse in review['verses'][1:4]:
 start=verse['start_tick']+9*q
 for gift in range(verse['day'],1,-1):
  actual=[(a-start,b-start,p) for a,b,p in lead if start<=a<start+3*q]
  assert actual==[(0,q,74),(q,q*3//2,69),(q*3//2,q*2,71),(q*2,q*3,72)],(verse['day'],gift,actual)
  start+=3*q
for verse in review['verses'][4:]:
 start=verse['start_tick']+9*q+(verse['day']-5)*3*q+8*q
 assert [p for a,b,p in lead if start<=a<start+3*q]==[74,72,71,69,67]
 start+=3*q
 assert [p for a,b,p in lead if start<=a<start+3*q]==[72,64,67]
 start+=3*q
 assert [p for a,b,p in lead if start<=a<start+3*q]==[69,67,66,64,62]
print('PASS Twelve Days: early gifts in verses2-4; three later variants in verses5-12')
assert len(songs)==46 and len({s['title']for s in songs})==46
assert read('MusicKeys')['songs'][45]['keys'][0][1:]==[-2,1]
assert tr[45]['meters']==[[0,9,8],[1920,12,8],[4224,9,8],[5952,12,8]]
print('PASS 46 unique songs; Gabriel G minor, eighth pickup and compound bar map')
# Native actual sample bank; MOD sample names map to independently stored base pitches.
bank=runpy.run_path(str(ROOT/'BuildTrackers'))['samples'](ROOT)
known={s['name']:s for s in bank}
for name in ['ClubSources','TranceSrc']:known.update({s['name']:s for s in read(name)['samples']})
changed=[];attacks=0
for meta in read('TrackerModes')['tracks']:
 if meta['song'] not in (22,43,44,45):continue
 s=songs[meta['song']];folder=['Chill','Dance','Class','Trance'][meta['style']-1]
 path=DIST/'!Xmas26/Tracker'/folder/f'C{meta["song"]+1:02}'
 raw=path.read_bytes();assert raw[1080:1084]==b'8CHN'
 slots=['']+[raw[20+i*30:42+i*30].split(b'\0')[0].decode()for i in range(31)]
 order=raw[952:952+raw[950]];rows=b''.join(raw[1084+p*2048:1084+(p+1)*2048]for p in order)
 timing=(path.parent/f'M{meta["song"]+1:02}').read_bytes();points=list(struct.iter_unpack('<ii',timing[20:]));assert len(points)==len(rows)//32+1
 expected=[(a,b,p)for a,b,p in s['streams'][0]if p>=0]
 primary=[p for p in meta['primary']if p['channel']==0]
 assert [(p['source_start_cs'],p['source_end_cs'],p['pitch'])for p in primary]==expected
 for n in primary:
  pos=n['start_row'];a,b,c,d=rows[pos*32:pos*32+4];sid=(a&240)|(c>>4);period=(a&15)*256+b
  sample=known[slots[sid]];wanted=round(sample['period']*2**((sample['base']-n['pitch'])/12))
  assert period==wanted,(path.name,n['pitch'],period,wanted)
  assert abs(points[pos][1]-n['source_start_cs'])<=2
  attacks+=1
 ms=0.;speed=6;bpm=125
 for pos in range(len(rows)//32):
  for ch in range(8):
   a,b,c,d=rows[pos*32+ch*4:pos*32+ch*4+4]
   if c&15==15:
    if d<32:speed=d
    else:bpm=d
  assert abs(points[pos][0]-ms)<=.51,(path,pos,points[pos][0],ms)
  ms+=2500*speed/bpm
 assert abs(points[-1][0]-ms)<=.51
 changed.append((path,meta['duration_cs']/100))
print(f'PASS {len(changed)} new/changed MODs, {attacks} melody attacks and exact command-derived clocks')
ap=argparse.ArgumentParser();ap.add_argument('--render',action='store_true');args=ap.parse_args()
if args.render:
 import numpy as np
 lib=ctypes.CDLL(ctypes.util.find_library('openmpt'))
 create=lib.openmpt_module_create_from_memory;create.restype=ctypes.c_void_p;create.argtypes=[ctypes.c_void_p,ctypes.c_size_t,ctypes.c_void_p,ctypes.c_void_p,ctypes.c_void_p]
 duration=lib.openmpt_module_get_duration_seconds;duration.argtypes=[ctypes.c_void_p];duration.restype=ctypes.c_double
 render=lib.openmpt_module_read_interleaved_float_stereo;render.argtypes=[ctypes.c_void_p,ctypes.c_int32,ctypes.c_size_t,ctypes.c_void_p];render.restype=ctypes.c_size_t
 destroy=lib.openmpt_module_destroy;destroy.argtypes=[ctypes.c_void_p]
 for path,seconds in changed+[(DIST/'!Xmas26/Tracker/NeonMOD',read('TrackerData')['seconds'])]:
  raw=path.read_bytes();buf=ctypes.create_string_buffer(raw);ptr=create(buf,len(raw),None,None,None);assert ptr,path
  actual=duration(ptr);assert abs(actual-seconds)<1,(path,actual,seconds)
  out=np.empty((4096,2),np.float32);frames=0;energy=0.;peak=0.
  for _ in range(math.ceil((actual+1)*12000/4096)):
   n=render(ptr,12000,4096,out.ctypes.data)
   if not n:break
   assert np.isfinite(out[:n]).all();frames+=n;energy+=float(np.square(out[:n]).sum());peak=max(peak,float(np.abs(out[:n]).max()))
  # libopenmpt rounds each tracker tick to whole samples at this QA rate.
  destroy(ptr);assert abs(frames/12000-actual)<1.5 and energy/frames>.000001,(path,actual,frames/12000,energy)
  print(f'RENDER {path.parent.name}/{path.name}: {actual:.2f}s, peak {peak:.3f}')
 print('PASS independent complete audio rendering of 16 changed/additional MODs and medley')
