"""184 complete eight-channel MOD arrangements, with score-position row maps.
Every MOD row is one tracker tick: 24 rows per musical quarter note. Tempo
changes are actual Fxx commands. A row map is generated from those commands,
not a constant-tempo estimate. Club/pop preserve the full melody with newly
arranged backing; the classical three-voice arranger is retained unchanged.
"""
from pathlib import Path
import json,struct,math,bisect,hashlib,runpy
ROOT=Path(__file__).resolve().parent
CLOCK=3546894.6
STYLES=['Chill','Dance','Class','Trance']
LABELS=['Electronic Chillout','90s PC-Pop','Classical Instruments','Dance/Trance']
CLUB=None
CLUB_BANK=None
TRANCE_BANK=None

def samples(root):
 b=(root/'SampleBank').read_bytes();assert b[:8]==b'X26S\x01\0\0\0';n=struct.unpack_from('<I',b,8)[0];at=12;out=[]
 for i in range(n):
  name=b[at:at+24].split(b'\0')[0].decode();base,period,volume,ls,ll,size=struct.unpack_from('<6I',b,at+24);at+=48
  out.append(dict(name=name,base=base,period=period,volume=volume,loop_start=ls,loop_length=ll,pcm=b[at:at+size]));at+=size
 assert at==len(b);return out

class ScoreClock:
 def __init__(self,song,source):
  self.division=source['division'];self.map=[];elapsed=0;prev=0;tempo=source['tempo'][0][1]
  for tick,value in source['tempo']:
   elapsed+=(tick-prev)/self.division*tempo/10000
   self.map.append((tick/self.division,elapsed,value));prev=tick;tempo=value
 def beat(self,cs):
  b,t,tempo=next(x for x in reversed(self.map) if x[1]<=cs)
  return b+(cs-t)/(tempo/10000)
 def cs(self,beat):
  b,t,tempo=next(x for x in reversed(self.map) if x[0]<=beat)
  return t+(beat-b)*tempo/10000
 def bpm(self,beat):
  return 60000000/next(x[2] for x in reversed(self.map) if x[0]<=beat)

def bar_at(tick,meters,division):
 beat=tick/24;bars=0;previous=0;barlen=4;pulse=1
 for at,n,d in meters:
  pos=at/division
  if pos>beat:break
  bars+=max(0,(pos-previous)/barlen);previous=pos;barlen=n*4/d
  pulse=1.5 if d==8 and n in (6,9,12) else (4/d if d>=4 else 1)
 local=(beat-previous)/barlen
 return int(bars+local), (beat-previous)%barlen,barlen,pulse

def build_one(song,source,style,index,bank):
 global CLUB,CLUB_BANK,TRANCE_BANK
 if style in (0,1,3):
  if CLUB is None:
   CLUB=runpy.run_path(str(ROOT/'ClubArrange'))
   CLUB_BANK=runpy.run_path(str(ROOT/'ClubSamples'))['build_bank']()
  if style==3:
   if TRANCE_BANK is None:TRANCE_BANK=runpy.run_path(str(ROOT/'TranceBank'))['build_bank']()
   return CLUB['build_one'](song,source,style,index,TRANCE_BANK,ScoreClock)
  return CLUB['build_one'](song,source,style,index,CLUB_BANK,ScoreClock)
 clock=ScoreClock(song,source);meters=source.get('meters') or [[0,4,4]];div=source['division']
 intro=song.get('tracker_intro_beats',(4,8,4)[style])*24;outro=(8,8,4)[style]*24
 endcs=max(b for st in song['streams'] for a,b,n in st if n>=0)
 body=round(clock.beat(endcs)*24);rows=math.ceil((intro+body+outro)/64)*64
 if rows>8192:rows=math.ceil(rows/128)*128
 assert rows<=16384 and rows>0
 mix=[1.25,1.15,1.50][style]
 events={};primary=[];ids={s['name']:i+1 for i,s in enumerate(bank)}
 def event(row,ch,name=None,note=60,gain=1,fx=None,replace=False):
  row=int(row)
  if not 0<=row<rows:return
  old=events.get((row,ch))
  if old is not None and not replace:return
  sid=ids[name] if name else 0
  volume=round(bank[sid-1]['volume']*gain*mix) if sid else 0
  events[row,ch]=[sid,note if sid else 0,12 if fx is None else fx[0],min(64,max(0,volume)) if fx is None else fx[1]]
 def cut(row,ch):event(row,ch,fx=(12,0))
 def energy(tick):
  bar,beat,barlen,pulse=bar_at(max(0,tick),meters,div)
  phase=bar%16
  return ([.70,.80,.92,.75][phase//4] if style==0 else [.78,.94,.66,1.0][phase//4] if style==1 else .82+.14*math.sin((bar%8)/8*math.pi)),bar
 voices=[['Velvet EP','Warm Sub','Aurora Pad'],['Neon Lead','Pulse Bass','Velvet EP'],['VSCO Flute','VSCO Cello','VSCO Viola']][style]
 quantised=[]
 for ch,st in enumerate(song['streams']):
  part=[]
  for a,b,n in st:
   aa=round(clock.beat(a)*24);bb=min(body,round(clock.beat(b)*24))
   if n<0 or bb<=aa or aa>=body:continue
   part.append([aa,bb,n]);e,bar=energy(aa);name=voices[ch]
   if ch==0:
    if style==0 and (bar//8+index)%2:name='Crystal Keys'
    if style==1 and (bar//8+index)%3==1:name='Crystal Keys'
    if style==2:name=['VSCO Flute','VSCO Oboe','VSCO Clarinet'][(bar//8+index)%3]
   gain=e*([1.0,.77,.60][ch] if style<2 else [1.04,.80,.77][ch])
   event(intro+aa,ch,name,n,gain,replace=True)
   # Two-tick release approaches the written end, avoiding hard loop clicks.
   v=min(64,round(bank[ids[name]-1]['volume']*gain*mix))
   for rr,level in [(bb-2,.62),(bb-1,.29)]:
    if rr>aa:event(intro+rr,ch,fx=(12,round(v*level)))
   cut(intro+bb,ch)
   primary.append(dict(channel=ch,start_row=intro+aa,end_row=intro+bb,pitch=n,source_start_cs=a,source_end_cs=b))
  quantised.append(part)
 # When a new attack shares the old note's end, retain the new note, not C00.
 for ch,part in enumerate(quantised):
  assert len(part)==sum(1 for e in primary if e['channel']==ch)
 def tones(tick):
  result=[]
  for st in quantised:
   # The arrangement is short enough for this build-time scan; no runtime search.
   active=next((n for a,b,n in st if a<=tick<b),None)
   if active is None:
    active=next((n for a,b,n in reversed(st) if a<=tick),None)
   if active is None:active=st[0][2] if st else 60
   result.append(active)
  return result
 # Responsive backing follows the real score/meter, including 3/4, 6/8 and changes.
 for t in range(body):
  e,bar=energy(t);barno,beat,barlen,pulse=bar_at(t,meters,div);phase=t/24
  pulse_tick=round(pulse*24);in_pulse=round(beat*24)%pulse_tick
  pulse_no=int(round(beat*24)//pulse_tick);down=abs(beat)<.001
  if t%6 and not down:continue
  row=intro+t;mel,bass,harm=tones(t);chord=sorted({48+n%12 for n in (bass,harm,mel)})
  if style==0:
   if t%24==0 and bar%4 in (0,2):
    event(row,3,'VSCO Piano',harm,.40*e);cut(row+min(20,body-t),3)
   if t%12==6 and bar%8 in (2,3,5,6):
    note=chord[(t//12+index)%len(chord)]+12
    event(row,4,'Glitter Pluck',note,.36*e)
   if in_pulse==0 and (pulse_no%2==0):event(row,5,'Deep Kick',gain=.65*e)
   if in_pulse==0 and pulse_no%2==1:event(row,6,'Brush Snare',gain=.55*e)
   if in_pulse==pulse_tick//2:event(row,7,'Sleigh Shimmer' if pulse_no%2 else 'Silk Hat',gain=.50*e)
  elif style==1:
   if t%12==0:
    event(row,3,'Glitter Pluck',harm,.55*e);cut(row+8,3)
   if t%6==0 and bar%8 not in (0,4):
    note=chord[(t//6+index)%len(chord)]+12
    event(row,4,'Crystal Keys',note,.34*e);cut(row+5,4)
   if in_pulse==0 and not (bar%16==8 and pulse_no%2):event(row,5,'Deep Kick',gain=.94*e)
   if in_pulse==0 and (pulse_no%2 or (barlen==3 and pulse_no==2)):event(row,6,'Pop Clap',gain=.95*e)
   if in_pulse==pulse_tick//2:event(row,7,'Air Hat',gain=.75*e)
   elif t%6==0:event(row,7,'Silk Hat',gain=(.33 if t%12 else .48)*e)
   if beat>barlen-.5 and bar%4==3 and t%6==0:event(row,6,'Brush Snare',gain=.6*e,replace=True)
   if down and bar%8==0:event(row,7,'Silver Crash',gain=.55*e,replace=True)
  else:
   if down:
    event(row,3,'VSCO Violin',harm+12,.48*e);cut(row+round(barlen*24)-2,3)
    event(row,5,'VSCO Piano',bass+12,.42*e)
   if in_pulse==0 and (pulse_no%2 or bar%4==3):
    note=chord[(pulse_no+bar)%len(chord)]+12
    event(row,4,'VSCO Harp',note,.42*e)
   if down and bar%8==0:event(row,6,'VSCO Glock',mel+12,.45*e)
   if down and bar%4==0:event(row,7,'Soft Timpani',gain=.35*e)
 # Introductions and endings use each song's own opening/closing harmony.
 for start,duration,tonepos,ending in [(0,intro,0,False),(intro+body,rows-intro-body,body-1,True)]:
  mel,bass,harm=tones(tonepos);chord=sorted({48+n%12 for n in (bass,harm,mel)})
  for t in range(0,duration,12):
   fadeout=max(0,1-t/duration)**1.4 if ending else .7+t/duration*.2
   note=chord[(t//12)%len(chord)]+12
   event(start+t,4,'VSCO Harp' if style==2 else 'Velvet EP' if style==0 else 'Glitter Pluck',note,.50*fadeout)
   if t%48==0:
    event(start+t,3,'VSCO Violin' if style==2 else 'Aurora Pad',harm,.38*fadeout)
   if style==1 and not ending and t%24==0:event(start+t,5,'Deep Kick',gain=.55)
  if ending:
   for ch in range(3):cut(start,ch)
   event(start,1,'VSCO Cello' if style==2 else 'Warm Sub',bass,.62)
 for ch in range(8):event(rows-1,ch,fx=(12,0),replace=True)
 # Explicit initial state; pan centres the rhythm and spreads supporting voices.
 pans=[118,128,68,190,175,128,145,195]
 for ch in range(8):event(1,ch,fx=(8,pans[ch]),replace=True)
 event(0,6,fx=(15,1),replace=True)
 original=clock.bpm(0)
 target=(min(104,max(72,original*.8))+(index%5-2) if style==0 else min(144,max(118,original*1.20))+(index%5-2) if style==1 else original)
 scale=target/original;tempos=[];mapping=[];ms=0.;prev=-1
 for row in range(rows):
  bodyrow=row-intro;beat=max(0,min(bodyrow,body)/24)
  bpm=clock.bpm(beat)*scale
  # Classical phrasing ends with a real, gradual ritardando; other styles keep groove.
  if style==2 and bodyrow>body-8*24:
   bpm*=1-.20*min(1,max(0,(bodyrow-(body-8*24))/(8*24)))
  bpm=max(32,min(255,round(bpm)))
  if bpm!=prev:event(row,7,fx=(15,bpm),replace=True);tempos.append([row,bpm]);prev=bpm
  sourcecs=round(clock.cs(bodyrow/24)) if 0<=bodyrow<body else -1
  mapping.append((round(ms),sourcecs));ms+=2500/bpm
 mapping.append((round(ms),-1))
 # Prune unused samples without changing either the notes or the source sample bank.
 packer=runpy.run_path(str(ROOT/'PackRows'))
 events,rows,mapping,speed=packer['pack'](events,rows,mapping)
 used=sorted({e[0] for e in events.values() if e[0]});newids={sid:i+1 for i,sid in enumerate(used)};selected=[bank[sid-1] for sid in used]
 title=(('CHILL ','DANCE ','CLASS ')[style]+song['title']).encode('ascii')[:20]
 out=bytearray(title.ljust(20,b'\0'))
 for i in range(31):
  if i<len(selected):
   s=selected[i];out+=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))
  else:out+=bytes(28)+b'\0\1'
 n=rows//64;out+=bytes([n,0])+bytes(range(n)).ljust(128,b'\0')+b'8CHN'
 for row in range(rows):
  for ch in range(8):
   sid,note,fx,value=events.get((row,ch),[0,0,0,0]);period=0
   if sid:
    s=bank[sid-1];period=round(s['period']*2**((s['base']-note)/12));assert 1<=period<=4095
    sid=newids[sid]
   out+=bytes([(sid&240)|(period>>8),period&255,((sid&15)<<4)|fx,value])
 out+=b''.join(s['pcm'] for s in selected)
 timing=b'X26R'+struct.pack('<4I',1,rows,style+1,index)+b''.join(struct.pack('<ii',*r) for r in mapping)
 assert len(timing)<=65556
 meta=dict(title=song['title'],style=style+1,label=LABELS[style],song=index,rows=rows,intro_rows=intro,body_rows=body,tempo=tempos[0][1],tempo_changes=tempos,duration_cs=round(mapping[-1][0]/10),samples=[s['name'] for s in selected],primary=primary)
 return bytes(out),timing,packer['metadata'](meta,speed)

def build(root=ROOT):
 bank=samples(root);songs=json.loads((root/'MusicData').read_text())['songs'];sources=json.loads((root/'TrackerInput').read_text())['songs'];catalogue=[]
 phrasing=json.loads((root/'LyricInput').read_text())['songs']
 rhythm=json.loads((root/'RhythmSources').read_text())['songs']
 for style,folder in enumerate(STYLES):
  dest=root.parent.parent/'!Xmas26/Tracker'/folder;dest.mkdir(exist_ok=True)
  for index,(song,source) in enumerate(zip(songs,sources)):
   assert song['title']==source['title']
   if style in (0,1,3):
    source=dict(source,pickup_beats=rhythm[index]['pickup_beats'])
    cues=phrasing[index]['cues']
    source['phrase_cs']=[cues[j+1][0] for j,cue in enumerate(cues[:-1]) if cue[1].rstrip().endswith((',', ';', '.', '!', '?', ':'))]
   module,timing,meta=build_one(song,source,style,index,bank)
   (dest/f'C{index+1:02}').write_bytes(module);(dest/f'M{index+1:02}').write_bytes(timing)
   meta['sha256']=hashlib.sha256(module).hexdigest();catalogue.append(meta)
  print('Built',LABELS[style],': '+str(len(songs))+' complete songs',flush=True)
 indexdata=b'X26I'+struct.pack('<III',1,len(songs),len(STYLES))+b''.join(struct.pack('<III',m['duration_cs'],m['rows'],m['tempo']) for m in catalogue)
 (root.parent.parent/'!Xmas26/Tracker/Index').write_bytes(indexdata)
 (root/'TrackerModes').write_text(json.dumps(dict(rows_per_quarter=24,speed=1,styles=LABELS,tracks=catalogue),separators=(',',':'))+'\n')
 if CLUB_BANK is not None:
  samplemeta=[dict({k:v for k,v in sample.items() if k!='pcm'},size_bytes=len(sample['pcm']),sha256=hashlib.sha256(sample['pcm']).hexdigest()) for sample in CLUB_BANK]
  (root/'ClubSources').write_text(json.dumps(dict(version='2.26',date='2026-11-02',samples=samplemeta,source='Original procedural synthesis in ClubSamples; original arrangements in ClubArrange. Existing carol melody sources remain in MusicSources. No external audio, loops, artist recordings or new third-party licences.'),indent=2)+'\n')
 if TRANCE_BANK:
  manifest=[dict({k:v for k,v in sample.items() if k!='pcm'}, size_bytes=len(sample['pcm']), sha256=hashlib.sha256(sample['pcm']).hexdigest()) for sample in TRANCE_BANK]
  (root/'TranceSrc').write_text(json.dumps(dict(source='build/TranceBank; build/TranceParts; build/ClubArrange', licence='MIT, see License. All sample PCM synthesised for OakAcorn Software from oscillators and seeded noise. No third-party audio inputs.', samples=manifest),indent=2)+'\n')
 return catalogue
if __name__=='__main__':
 data=build();print('Built',len(data),'MODs;',sum(t['duration_cs'] for t in data)/6000,'minutes; max',max(t['rows'] for t in data),'rows')
