"""Build editable DJ decks from the shipped 8-channel Dance/Trance MODs.
One shared QTM sample bank, a 24-row beat grid and per-row instrument states.
No audio is rendered or time-stretched. Instrument pitches are retained.
"""
from pathlib import Path
import hashlib, json, struct, runpy
import numpy as np

ROOT=Path(__file__).resolve().parent
TRACK=ROOT.parent.parent/'!Xmas26/Tracker'
BEAT=12
OVERLAP=8*BEAT
RING=7680
HEADER=struct.Struct('<4s8I')

def note(sid,period,volume):
    return bytes(((sid&16)|(period>>8), period&255, (sid&15)*16+12, volume))

def slot(event):
    return (int(event[0])&16)|(int(event[2])>>4)

def period(event):
    return ((int(event[0])&15)<<8)|int(event[1])

def build():
    dest=TRACK/'Mix';dest.mkdir(exist_ok=True)
    bank=runpy.run_path(str(ROOT/'TranceBank'))['build_bank']()
    ids={s['name']:i+1 for i,s in enumerate(bank)}
    kit=bytearray(b'OAKACORN DJ DECK'.ljust(20,b'\0'))
    for i in range(31):
        if i>=len(bank):kit+=bytes(28)+b'\0\1';continue
        s=bank[i]
        kit+=s['name'].encode().ljust(22,b'\0')+struct.pack('>HBBHH',len(s['pcm'])//2,0,s['volume'],s['loop_start']//2,max(1,s['loop_length']//2))
    kit+=bytes((120,0))+bytes(range(120))+bytes(8)+b'8CHN'+bytes(RING*32)
    kit+=b''.join(s['pcm'] for s in bank)
    (dest/'DJDeck').write_bytes(kit)
    tracks=json.loads((ROOT/'TrackerModes').read_text())['tracks']
    for m in tracks:
        if m['style']!=4:continue
        i=m['song'];raw=(TRACK/'Trance'/f'C{i+1:02}').read_bytes()
        pcm_start=1084+m['rows']*32
        remap={}
        for k in range(31):
            length=struct.unpack_from('>H',raw,42+k*30)[0]*2
            if length:
                name=raw[20+k*30:42+k*30].split(b'\0')[0].decode()
                remap[k+1]=ids[name]
                assert raw[pcm_start:pcm_start+length]==bank[ids[name]-1]['pcm']
                pcm_start+=length
        assert pcm_start==len(raw)
        pulse=m['kick_pulse_rows'];bpm=m['dance_bpm']
        pickup=m['bars'][0]['end'] if m['bars'][0]['pickup'] else 0
        pad=(-round((m['intro_rows']+pickup)*BEAT/pulse))%BEAT
        def norm(r):return pad+(r*BEAT+pulse//2)//pulse
        cut=((norm(m['intro_rows']+m['body_rows'])+4*BEAT-1)//(4*BEAT))*(4*BEAT)
        count=cut+OVERLAP; rows=np.zeros((count,8,4),dtype='u1')
        src=np.frombuffer(raw[1084:1084+m['rows']*32],dtype='u1').reshape(-1,8,4)
        # Merge a volume update landing on an attack without erasing the note.
        for r,events in enumerate(src):
            destrow=norm(r)
            if destrow>=cut:break
            for ch,event in enumerate(events):
                sid=slot(event);fx=int(event[2])&15
                if sid:
                    new=remap[sid];rows[destrow,ch,:2]=((new&16)|(int(event[0])&15),event[1])
                    rows[destrow,ch,2]=new%16*16+(int(rows[destrow,ch,2])&15)
                if fx==12 or sid:
                    volume=int(event[3]) if fx==12 else bank[remap[sid]-1]['volume']
                    rows[destrow,ch,2]=(int(rows[destrow,ch,2])&240)|12;rows[destrow,ch,3]=volume
        # Use a common, continuous downbeat and the original track's last chord.
        rows[:,5]=0
        last={}
        for r in range(cut):
            for ch in (0,1,2,3):
                if slot(rows[r,ch]):last[ch]=rows[r,ch].copy()
        for r in range(count):
            if r%BEAT==0:rows[r,5]=list(note(ids['Vector Kick'],160,55))
            if r<cut:continue
            off=r-cut; gain=min(1,(count-r)/(2*BEAT))
            for ch,base,offset,step,vol in [(2,2,0,BEAT,21),(1,1,BEAT//2,BEAT,37),(4,0,0,2*BEAT,17)]:
                if off%step==offset and base in last:
                    e=last[base];rows[r,ch]=list(note(slot(e),period(e),round(vol*gain)))
            if off%(2*BEAT)==BEAT:rows[r,6]=list(note(ids['Photon Clap'],160,round(37*gain)))
            if off%(BEAT//2)==0:rows[r,7]=list(note(ids['Ion Open'] if off%BEAT else ids['Ion Closed'],160,round((26 if off%BEAT else 16)*gain)))
        # The musical clock is carried explicitly: a score position for each DJ row.
        timing=(TRACK/'Trance'/f'M{i+1:02}').read_bytes()
        srcmap=np.frombuffer(timing[20:],dtype='<i4').reshape(-1,2)
        position=np.full(count,-1,dtype='<i4')
        for r in range(pad,cut):
            old=((r-pad)*pulse+BEAT//2)//BEAT
            if old<m['rows']:position[r]=srcmap[old,1]
        # Preserve panning and register both tempo and speed on separate channels.
        rows[1,:,2]=8;rows[1,:,3]=[128,128,68,188,204,128,146,179]
        for ch,val in [(6,2),(7,bpm)]:
            rows[0,ch,2]=(int(rows[0,ch,2])&240)|15;rows[0,ch,3]=val
        # Seekable snapshots preserve sounding notes while the overlap reassigns lanes.
        states=np.zeros((count,3,4),dtype='u1')
        for ch in range(3):
            sid=per=vol=0
            for r in range(count):
                e=rows[r,ch]
                if slot(e):sid=slot(e);per=period(e);vol=bank[sid-1]['volume']
                if int(e[2])&15==12:vol=int(e[3])
                states[r,ch]=list(note(sid,per,vol))
        assert count+16*BEAT+128<RING and cut>=OVERLAP+96
        (dest/f'J{i+1:02}').write_bytes(HEADER.pack(b'DJ41',2,i,bpm,pulse,pad,cut,count,m['rows'])+rows.tobytes()+states.tobytes()+position.tobytes())
    print('Built QTM deck and 46 beat-aligned, pitch-preserving DJ arrangements.')
if __name__=='__main__':build()
