"""Check the v2.26 arrangements independently from the arranger's metadata.
Run: python3 CheckClub [path-to-v2.25-source-tree]
For a full audio decode/headroom check also use python3 CheckModules.
The optional v2.25 baseline covers music inputs/outputs; current UI and
artwork may have evolved independently. Maestro exports now live beside the app.
"""
from pathlib import Path
from collections import Counter
import json, math, struct, sys
import numpy as np

root=Path(__file__).resolve().parent
tracks=json.loads((root/'TrackerModes').read_text())['tracks']
songs=json.loads((root/'MusicData').read_text())['songs']
sources=json.loads((root/'TrackerInput').read_text())['songs']
samplemeta={s['name']:s for s in json.loads((root/'ClubSources').read_text())['samples']}
baseline=Path(sys.argv[1]) if len(sys.argv)>1 else None
events=0;boundaries=0;max_error=0.;loop_count=0;families=Counter()
for track in tracks[:86]:
    song=songs[track['song']];source=sources[track['song']]
    folder=('Chill','Dance')[track['style']-1]
    path=root.parent.parent/'!Xmas26/Tracker'/folder/f"C{track['song']+1:02}"
    raw=path.read_bytes();native={};data=1084+track['rows']*32
    for i in range(31):
        name=raw[20+i*30:42+i*30].split(b'\0')[0].decode()
        size,fine,volume,ls,ll=struct.unpack_from('>HBBHH',raw,42+i*30)
        if not size:continue
        assert fine==0 and volume<=64
        native[i+1]=samplemeta[name]
        pcm=np.frombuffer(raw[data:data+size*2],dtype='i1').astype(float);data+=size*2
        if ll>1:
            start,end=ls*2,(ls+ll)*2
            assert 0<start<end<=len(pcm)
            step=abs(pcm[end-1]-pcm[start])
            slope=np.percentile(abs(np.diff(pcm[start:end])),99)
            assert step<=slope*2+3,(name,'loop discontinuity',step,slope)
            loop_count+=1
    assert data==len(raw)
    body=np.frombuffer(raw[1084:1084+track['rows']*32],dtype=np.uint8).reshape(-1,8,4)
    sid=(body[:,:,0]&240)|(body[:,:,2]>>4)
    period=((body[:,:,0].astype(int)&15)<<8)|body[:,:,1]
    effect=body[:,:,2]&15;value=body[:,:,3]
    timing=path.with_name('M'+path.name[1:]).read_bytes()
    points=np.frombuffer(timing[20:],dtype='<i4').reshape(-1,2)
    assert len(points)==track['rows']+1
    tempo=125;speed=6;ms=0.;volume=0
    source_notes=[(a,b,n) for a,b,n in song['streams'][0] if n>=0 and b>a]
    recorded=[(n['source_start_cs'],n['source_end_cs'],n['pitch']) for n in track['primary']]
    assert recorded==source_notes,(track['title'],'changed/missing melody')
    active=np.zeros(track['rows'],bool)
    # Reconstruct source musical quarters at each lyric/source-clock position.
    tempo_segments=[];cs=0.;prev=0;micro=source['tempo'][0][1]
    for tick,new in source['tempo']:
        cs+=(tick-prev)/source['division']*micro/10000
        tempo_segments.append((tick/source['division'],cs,new));prev=tick;micro=new
    def source_beats(cs):
        b,t,m=next(p for p in reversed(tempo_segments) if p[1]<=cs+1e-7)
        return b+(cs-t)*10000/m
    meter_segments=[];arr=0.;previous_beat=0.;factor=1.
    for tick,n,d in source.get('meters') or [[0,4,4]]:
        beat=tick/source['division'];arr+=(beat-previous_beat)*factor
        factor=1.
        meter_segments.append((beat,arr,factor));previous_beat=beat
    def expected_row(cs):
        beat=source_beats(cs);b,a,f=next(p for p in reversed(meter_segments) if p[0]<=beat+1e-7)
        return track['intro_rows']+round((a+(beat-b)*f)*24)
    for note in track['primary']:
        row=note['start_row'];end=note['end_row']
        assert row==expected_row(note['source_start_cs']) and end==expected_row(note['source_end_cs'])
        sample=native[int(sid[row,0])]
        wanted=round(sample['period']*2**((sample['base']-note['pitch'])/12))
        assert period[row,0]==wanted,(track['title'],note,'wrong melody pitch')
        error=abs(points[row,1]-note['source_start_cs']);max_error=max(max_error,error)
        assert error<=2,(track['title'],'lyric clock drift',error)
        active[row:end]=True;events+=1;boundaries+=2
    for row in range(track['rows']):
        for ch in range(8):
            if effect[row,ch]==15:
                if value[row,ch]<32:speed=int(value[row,ch])
                else:tempo=int(value[row,ch])
        assert speed==1 and abs(points[row,0]-ms)<=.51
        ms+=2500/tempo
        if sid[row,0]:volume=native[int(sid[row,0])]['volume']
        if effect[row,0]==12:volume=int(value[row,0])
        if not active[row]:assert volume==0,(track['title'],row,'melody note leaked across rest')
    assert abs(points[-1,0]-ms)<=.51
    assert all(s['row']-track['intro_rows'] in track['phrase_rows'] for s in track['sections'])
    assert len(set(sid[n['start_row'],0] for n in track['primary']))==1,(track['title'],'lead changes within song')
    families[(track['style'],track['arrangement'])]+=1
    if baseline:
        assert path.read_bytes()!=(baseline/path.relative_to(root.parent.parent)).read_bytes()
assert len(families)==8,families
unchanged=0
if baseline:
    for parent in ('!Xmas26/Tracker/Class','Maestros','MaestrosPluck'):
        for path in (root.parent.parent/parent).rglob('*'):
            if path.is_file():
                oldpath=baseline/path.relative_to(root.parent.parent)
                if parent.startswith('Maestros') and not oldpath.exists():oldpath=baseline/'!Xmas26'/path.relative_to(root.parent.parent)
                assert path.read_bytes()==oldpath.read_bytes();unchanged+=1
    for name in ('!Xmas26/Carols','!Xmas26/Lyrics','!Xmas26/NoteView','!Xmas26/KaraScore',
                 '!Xmas26/Tracker/NeonMOD','!Xmas26/Tracker/NeonDTT','!Xmas26/Tracker/QTMModule',
                 'SampleBank','MusicData','TrackerInput','Music','Playlist'):
        current=root.parent.parent/name if name.startswith('!Xmas26/') else root/name
        assert current.read_bytes()==(baseline/name).read_bytes(),name;unchanged+=1
    # Transport changes only to suppress VU work when animations are stopped.
    assert (root/'Tracker').read_text().replace(' AND animationsstopped%=FALSE','')==(baseline/'Tracker').read_text()
    previous=json.loads((baseline/'TrackerModes').read_text())['tracks']
    assert tracks[86:]==previous[86:]
print(f'PASS: 86 new electronic tracks; {events} unchanged melody attacks / {boundaries} score boundaries; maximum source-clock rounding {max_error:g} cs')
print(f'PASS: exact native row clocks, rests/releases, {loop_count} sample loop boundaries, eight arrangement families; {unchanged} protected files unchanged')
print(dict(families))
