from pathlib import Path
import ctypes as C,json,struct,math,numpy as np,sys
root=Path(__file__).resolve().parent;meta=json.loads((root/'TrackerModes').read_text())['tracks'];lib=C.CDLL('libopenmpt.so.0')
def api(name,ret,args):
 f=getattr(lib,'openmpt_module_'+name);f.restype=ret;f.argtypes=args;return f
create=api('create_from_memory2',C.c_void_p,[C.c_void_p,C.c_size_t]+[C.c_void_p]*7)
destroy=api('destroy',None,[C.c_void_p]);duration=api('get_duration_seconds',C.c_double,[C.c_void_p]);read=api('read_interleaved_float_stereo',C.c_size_t,[C.c_void_p,C.c_int32,C.c_size_t,C.c_void_p]);repeat=api('set_repeat_count',C.c_int,[C.c_void_p,C.c_int32]);seek=api('set_position_seconds',C.c_double,[C.c_void_p,C.c_double]);param=api('set_render_param',C.c_int,[C.c_void_p,C.c_int,C.c_int])
if "--new" in sys.argv:meta=[m for m in meta if m["song"]==42]
if "--song" in sys.argv:meta=[m for m in meta if m["song"]==int(sys.argv[sys.argv.index("--song")+1])]
results=[]
for m in meta:
 folder=['Chill','Dance','Class','Trance'][m['style']-1];p=root.parent.parent/'!Xmas26/Tracker'/folder/f"C{m['song']+1:02}";b=p.read_bytes();buf=C.create_string_buffer(b);mod=create(buf,len(b),None,None,None,None,None,None,None);assert mod
 d=duration(mod);assert abs(d-m['duration_cs']/100)<m['rows']*m.get('speed',1)/44100+.02,(p,d,m['duration_cs']/100)
 assert b[1080:1084]==b'8CHN' and b[950]*64==m['rows']
 samplebytes=0
 for i in range(31):
  length,fine,volume,loopstart,looplength=struct.unpack_from('>HBBHH',b,42+i*30)
  assert volume<=64 and fine<=15
  if looplength>1:assert loopstart+looplength<=length
  samplebytes+=length*2
 assert len(b)==1084+m['rows']*32+samplebytes
 mapb=p.with_name('M'+p.name[1:]).read_bytes();points=np.frombuffer(mapb[20:],dtype='<i4').reshape(-1,2);assert len(points)==m['rows']+1
 t=0;tempo=125;speed=6
 for row in range(m['rows']):
  for ch in range(8):
   e=b[1084+(row*8+ch)*4:1088+(row*8+ch)*4];fx=e[2]&15
   if fx==15:
    if e[3]<32:speed=e[3]
    else:tempo=e[3]
  assert speed==m.get('speed',1)
  assert abs(points[row,0]-t)<.51
  t+=2500*speed/tempo
 for n in m['primary']:
  row=n['start_row'];ch=n['channel'];e=b[1084+(row*8+ch)*4:1088+(row*8+ch)*4];sid=(e[0]&240)|(e[2]>>4);period=((e[0]&15)<<8)|e[1]
  assert sid and period,(p,n)
  assert abs(points[row,1]-n['source_start_cs'])<=2,(p,n,points[row])
 repeat(mod,0);param(mod,1,0) # no automatic gain boost
 peak=0;energy=0;frames=0
 arr=np.zeros((4096,2),np.float32)
 while True:
  size=read(mod,22050,4096,arr.ctypes.data)
  if not size:break
  x=arr[:size];peak=max(peak,float(abs(x).max()));energy+=float((x*x).sum());frames+=size
 assert peak>.015 and peak<.98,(p,peak)
 results.append(dict(style=m['style'],song=m['song'],duration=d,peak=peak,rms=math.sqrt(energy/(frames*2))))
 destroy(mod)
 if (m['song']+1)%14==0:print(folder,m['song']+1,'verified',flush=True)
Path('/tmp/xmas26-module-check.json').write_text(json.dumps(results,indent=2))
print('PASS:',len(results),'complete modules independently decoded/rendered; row clocks, attacks, tempo changes, duration and headroom',max(x['peak'] for x in results))
