"""Distinct club and contemporary pop arrangements of the complete carols.

The three electronic genres share the melody, clock and MOD encoder. The carol melody and its
score clock are retained; bass, chords, drums, echoes and section dynamics
are newly arranged. All DSP is baked into samples or ordinary MOD events.
"""
import bisect
import math
import struct
import runpy
from pathlib import Path

TRANCE = runpy.run_path(str(Path(__file__).with_name("TranceParts")))
from collections import defaultdict

FAMILIES = [
    ['Balearic house', 'Deep house', 'Downtempo breaks', 'Melodic house'],
    ['Dance pop', 'Synth pop', 'Tropical pop', 'Future pop']]

class ArrangementClock:
    """Keep score quarters intact; MIDI meter controls bars, never rescale notes."""
    def __init__(self, source, clock):
        self.clock=clock
        self.segments=[(tick/source['division'],tick/source['division'],1.)
                       for tick,n,d in source.get('meters') or [[0,4,4]]]
    def arrangement(self, beat): return beat
    def source(self, beat): return beat
    def row(self, cs): return round(self.clock.beat(cs)*24)
    def cs(self, row): return self.clock.cs(row/24)
    def bpm(self, row): return self.clock.bpm(max(0,row/24))

def meter_bars(source, body):
    """Native bar/pulse rows, including anacrusis and time-signature changes."""
    meters=source.get('meters') or [[0,4,4]];bars=[]
    for j,(tick,n,d) in enumerate(meters):
        start=round(tick/source['division']*24)
        limit=min(body,round(meters[j+1][0]/source['division']*24)) if j+1<len(meters) else body
        length=round(n*4/d*24);pulse=36 if d==8 and n%3==0 else round(96/d)
        if j==0 and source.get('pickup_beats',0):
            pickup=round(source['pickup_beats']*24)
            bars.append(dict(start=0,end=min(pickup,limit),length=length,pulse=pulse,meter=[n,d],pickup=True))
            start=pickup
        while start<limit:
            bars.append(dict(start=start,end=min(start+length,limit),length=length,pulse=pulse,meter=[n,d],pickup=False))
            start+=length
    return bars

def build_one(song, source, style, index, bank, score_clock):
    clock = ArrangementClock(source, score_clock(song, source))
    # Alternate families across the playlist, with one coherent palette per song.
    family=index%4
    pulse=1.5 if (source.get('meters') or [[0,4,4]])[0][2]==8 and (source.get('meters') or [[0,4,4]])[0][1]%3==0 else 1.
    trance=style==3
    club_pulse=round(24*pulse)
    native_pulse=clock.bpm(0)/pulse
    target=max(64,min(118,native_pulse*(.94,1.02,.88,1.06)[family])) if style==0 else max(90,min(146,native_pulse*(1.18,1.12,1.06,1.28)[family]))
    target=TRANCE["TEMPI"][family] if trance else target
    scale=target/native_pulse
    first_meter=(source.get('meters') or [[0,4,4]])[0]
    intro=round(song.get('tracker_intro_beats',first_meter[1]*4/first_meter[2])*24)
    end_cs=max(b for st in song['streams'] for a,b,n in st if n>=0)
    body=clock.row(end_cs);bars=meter_bars(source,body)
    rows=math.ceil((intro+body+bars[-1]['length'])/64)*64
    if rows>8192:rows=math.ceil(rows/128)*128
    assert 0<rows<=16384
    ids={s['name']:i+1 for i,s in enumerate(bank)}
    notes=[[] for _ in range(8)];primary=[];attacks=[];kicks=[];rhythm=[]
    total_bars=len(bars)
    # Punctuation/rest-derived phrase starts, not percentages through a melody.
    phrase_rows=sorted({0,*[clock.row(cs) for cs in source.get('phrase_cs',[]) if 0<clock.row(cs)<body]})
    phrase_notes=[(clock.row(a),clock.row(b)) for a,b,n in song['streams'][0] if n>=0]
    for left,right in zip(phrase_notes,phrase_notes[1:]):
        if right[0]-left[1]>=12:phrase_rows.append(right[0])
    phrase_rows=sorted(set(phrase_rows))
    if len(phrase_rows)<6:
        # Only a new melody attack at a barline is a safe fallback boundary.
        barstarts={b['start'] for b in bars}
        phrase_rows=sorted(set(phrase_rows)|{a for a,b in phrase_notes if a in barstarts})
    names=['verse','groove','breakdown','build','hook','finale']
    energies=[.76,.90,.57,.81,1.,.94]
    sections=[]
    for i,name in enumerate(names):
        idx=min(len(phrase_rows)-1,round(i*(len(phrase_rows)-1)/5))
        row=phrase_rows[idx]
        if sections and sections[-1]['row']==intro+row:continue
        sections.append(dict(row=intro+row,section=name,energy=energies[i]))
    def section(tick):
        sec=next(s for s in reversed(sections) if s['row']<=intro+max(0,tick))
        return sec['section'],sec['energy']
    serial = 0
    def note(row, channel, name, pitch=60, length=24, gain=1., shape='gate', priority=2):
        nonlocal serial
        row = int(round(row));length = max(1,int(round(length)))
        if row < 0 or row >= rows-1: return
        serial += 1
        notes[channel].append(dict(row=row,end=min(rows-1,row+length),sid=ids[name],
            pitch=pitch, gain=gain, shape=shape, priority=priority, serial=serial))
        if name in ('Club Kick','Pop Punch Kick','Vector Kick'): kicks.append(row)
    # Quantised source parts are used for harmony analysis, not copied as
    # organ-like sustained electronic bass/accompaniment voices.
    parts = []
    for stream in song['streams']:
        parts.append([(clock.row(a),min(body,clock.row(b)),n,a,b)
            for a,b,n in stream if n >= 0 and clock.row(b)>clock.row(a) and clock.row(a)<body])
    def at(ch, tick):
        active = next((n for a,b,n,_,_ in parts[ch] if a <= tick < b), None)
        if active is None:
            active = next((n for a,b,n,_,_ in reversed(parts[ch]) if a <= tick), None)
        return active if active is not None else parts[ch][0][2] if parts[ch] else 60
    # Estimate the local triad from duration-weighted score tones; passing
    # melody notes carry less weight than bass and the original harmony.
    histogram = [0.]*12
    for channel, part in enumerate(parts):
        for a,b,n,_,_ in part: histogram[n%12] += (b-a)*(1. if channel else .55)
    scales = [(False,(0,2,4,5,7,9,11)),(True,(0,2,3,5,7,8,10))]
    key, minor = max(((root,minor) for root in range(12) for minor,scale_notes in scales),
        key=lambda rm: sum(histogram[(rm[0]+p)%12] for p in scales[rm[1]][1])
            + sum(histogram)*(.09 if at(1,body-1)%12==rm[0] else 0))
    key_notes = {(key+p)%12 for p in scales[minor][1]}
    harmonies = {}
    harmonic_anchors=sorted({0,body,*[a for a,b,n,_,_ in parts[1]],*[m["start"] for m in bars]})
    def harmony(tick):
        tick = max(0,min(body-1,int(tick)))
        cell = max(0,bisect.bisect_right(harmonic_anchors,tick)-1)
        if cell in harmonies: return harmonies[cell]
        start=harmonic_anchors[cell];stop=harmonic_anchors[cell+1];weights=[0.]*12
        for ch,part in enumerate(parts):
            for a,b,n,_,_ in part:
                overlap=max(0,min(stop,b)-max(start,a))
                if overlap: weights[n%12] += overlap*(.32,1.0,.9)[ch]
        denom=max(1,sum(weights));weights=[v/denom for v in weights]
        bass=at(1,start)%12
        def fit(root,kind):
            pcs={(root+n)%12 for n in ((0,4,7),(0,3,7),(0,3,6))[kind]}
            return (sum(w if p in pcs else -.65*w for p,w in enumerate(weights))
                + (.20 if root==bass else 0) + .025*len(pcs & key_notes))
        root,kind=max(((r,k) for r in range(12) for k in range(3)),key=lambda rk:fit(*rk))
        quality=('Maj7','Min7','Dim')[kind]
        if kind==0 and (root+10)%12 in key_notes and (root+11)%12 not in key_notes: quality='Dom7'
        bass_note=36+root if root<8 else 24+root
        chord_note=bass_note+12
        tones=((0,4,7,11) if quality=='Maj7' else (0,3,7,10) if quality=='Min7'
               else (0,4,7,10) if quality=='Dom7' else (0,3,6,9))
        result=(bass_note,chord_note,quality,tones)
        harmonies[cell]=result
        return result
    leads=(('Velour EP','Dub Organ','Nylon Mist','Aurora Glass'),
           ('Wide Saw','FM Neon','Marimba Air','Vowel Cloud'))
    fixed_lead=TRANCE["LEADS"][family] if trance else leads[style][family]
    for a,b,pitch,source_start,source_end in parts[0]:
        role,e=section(a)
        name=fixed_lead
        gain=(.91 if style==0 else 1.04)*(.90+.10*e)
        note(intro+a,0,name,pitch,b-a,gain,'lead',4)
        primary.append(dict(channel=0,start_row=intro+a,end_row=intro+b,pitch=pitch,
            source_start_cs=source_start,source_end_cs=source_end,instrument=name))
        # Dotted or straight echoes alternate by family. They are quiet,
        # separately panned tracker notes, not a fixed-time baked delay.
        delay=(18,12,18,9)[family] if style==0 else (9,12,18,6)[family]
        if b-a>=8:
            note(intro+a+delay,4,name,pitch,min(b-a,24),.18 if style==0 else .11,'echo',0)
        attacks.append((a,pitch))
    bass_names=(('Round Sub','Deep Rubber Bass','Round Sub','Deep Rubber Bass'),
                ('Pop Pulse Bass','FM Bounce Bass','FM Bounce Bass','Round Sub'))
    if trance:
        rhythm=TRANCE['sequence'](note,harmony,section,sections,family,intro,body,rows,
            club_pulse,round(source.get('pickup_beats',0)*24))
        bass_name=('Rolling Sub','Phase Bass','Rolling Sub','Phase Bass')[family]
        pad_kind='Aurora';stab_kind='Laser Arp';counter='Air Lift'
    else:
        bass_name=bass_names[style][family]
        pad_kind='Silk' if family in (0,2) else 'Cloud'
        stab_kind='Felt' if style==0 and family in (0,2) else 'House' if style==0 else 'Pop'
        counter=('Aurora Glass','Nylon Mist','Velour EP','Poolside Pluck')[family] if style==0 else ('Marimba Air','FM Neon','Tropic Mallet','Silicon Hook')[family]
        for bar,measure in enumerate(bars):
            base=measure['start'];stop=measure['end'];length=stop-base;pulse=measure['pulse']
            if style==1 and pulse>36:pulse=24
            role,e=section(base);n,d=measure['meter']
            # One chord bed per actual pulse; eighth-note subdivisions in 6/8.
            for off in range(0,length,pulse):
                t=base+off;bass,chord,q,tones=harmony(t)
                note(intro+t,2,pad_kind+' '+q,chord,min(pulse,body-t),(.58 if style==0 else .48)*e,'pad')
            step=12 if d==8 else pulse//2
            for k,off in enumerate(range(0,length,step)):
                t=base+off;role,e=section(t);bass,chord,q,tones=harmony(t)
                pulse_no=off//pulse;within=off%pulse
                basshit=(within==0 or (within==step and family in (1,3)))
                if role=='breakdown':basshit=off==0
                if basshit:
                    pitch=bass+(12 if style==1 and family==1 and pulse_no%4==3 else 0)
                    note(intro+t,1,bass_name,pitch,min(pulse*.7 if role=='breakdown' else step*.8,body-t),(.90 if style==0 else 1.)*e,'bass')
                if within==step and (role!='breakdown' or pulse_no%2==0):
                    note(intro+t,3,stab_kind+' '+q,chord,min(step*.72,body-t),(.68 if style==0 else .85)*e,'stab')
                if role in ('groove','hook','finale') and within==step and pulse_no%2==family%2:
                    pitch=chord+12+tones[(bar+pulse_no+index)%len(tones)]
                    note(intro+t,4,counter,pitch,step*.7,(.21 if style==0 else .27)*e,'echo',1)
            kick='Club Kick' if style==0 else 'Pop Punch Kick'
            snare=('Dust Rim' if family in (0,2) else 'Club Clap') if style==0 else ('Pop Snap' if family==2 else 'Pop Snare')
            closed='Club Closed' if style==0 else 'Pop Closed';opened='Club Open' if style==0 else 'Pop Open'
            beats=list(range(0,length,pulse))
            for k,off in enumerate(beats):
                t=base+off;role,e=section(t)
                ispickup=measure['pickup']
                kickhit=not ispickup
                if family==2:kickhit=kickhit and (k%2==0)
                if style==1 and family==3:kickhit=kickhit and k%2==0
                if role=='breakdown':kickhit=kickhit and k==0 and bar%2==0
                if style==1:kickhit=True
                if kickhit:
                    note(intro+t,5,kick,length=min(pulse-1,22),gain=e*.95,shape='drum')
                    rhythm.append(dict(row=intro+t,kind='kick',bar=bar,pulse=k))
                backbeat=(k%2==1) or (len(beats)==3 and k==2 and style==1)
                if backbeat and (style==1 or (role!='breakdown' and not ispickup)):
                    note(intro+t,6,snare,length=min(pulse-1,18),gain=e*.92,shape='drum')
                    rhythm.append(dict(row=intro+t,kind='snare',bar=bar,pulse=k))
            hatstep=12 if d==8 else 6 if style==1 and family in (0,1,3) and role not in ('verse','breakdown') else pulse//2
            for k,off in enumerate(range(0,length,hatstep)):
                t=base+off;role,e=section(t)
                if style==0 and role=='breakdown' and k%2:continue
                offbeat=off%pulse!=0
                name=opened if offbeat and role in ('groove','hook','finale') and k%2 else closed
                if family==2 and offbeat:name='Soft Shaker'
                note(intro+t,7,name,length=min(hatstep-1,12),gain=(.58 if offbeat else .30)*e,shape='drum')
                rhythm.append(dict(row=intro+t,kind='hat',bar=bar,pulse=off/pulse))
            # Fills land on this measure's final pulse and its real subdivisions.
            nextrole=section(stop)[0] if stop<body else 'ending'
            if nextrole!=role and not measure['pickup']:
                for j,off in enumerate(range(max(0,length-pulse),length,max(3,pulse//6))):
                    note(intro+base+off,6,snare,length=3,gain=(.22+j*.07)*e,shape='drum',priority=3)
        # A sparse transition accent only at a scored phrase boundary.
        for sec in sections:
            if sec['section']=='hook':note(sec['row'],4,'Bright Splash',length=48,gain=.4,shape='drum',priority=5)
        # Brief bespoke opening and a resolving, fading ending. O Holy Night keeps
        # its explicitly zero-length additional intro from the previous correction.
        for start,duration,tick,ending in ((0,intro,0,False),(intro+body,rows-intro-body,body-1,True)):
            if duration<=0:continue
            bass,chord,q,tones=harmony(tick)
            note(start,2,pad_kind+' '+q,chord,duration,.60,'outro' if ending else 'pad')
            note(start,1,bass_name,bass,duration,.59,'outro' if ending else 'bass')
            for off in range(0,duration,24):
                gain=.34*(1-off/duration) if ending else .27+.20*off/duration
                note(start+off,3,fixed_lead,chord+12+tones[(off//24)%3],24,gain,'echo')
            if style==1:
                pulse=(bars[-1] if ending else bars[0])['pulse']
                if pulse not in (12,24,36):pulse=24
                for k,off in enumerate(range(0,duration,pulse)):
                    note(start+off,5,kick,length=min(pulse-1,22),gain=.83,shape='drum')
                    if k%2:note(start+off,6,snare,length=min(pulse-1,18),gain=.75,shape='drum')
                for k,off in enumerate(range(0,duration,max(1,pulse//2))):
                    note(start+off,7,closed if k%2==0 else opened,length=min(10,pulse//2),gain=.43,shape='drum')
            elif not ending:
                for off in range(12,duration,24):note(start+off,7,'Soft Shaker',length=10,gain=.40,shape='drum')
    # Resolve overlapping notes per channel before writing automation. An old
    # release can never cut a later note/echo. High-priority transitions occupy
    # their whole region instead of being chopped by a low-priority echo.
    events={};kicks.sort()
    for channel,sequence in enumerate(notes):
        byrow=defaultdict(list)
        for n in sequence:byrow[n['row']].append(n)
        active=None;previous_volume=-1
        for row in range(rows):
            if active is not None and row>=active['end']:active=None
            new=max(byrow[row],key=lambda n:(n['priority'],n['serial'])) if row in byrow else None
            if active and new and active['priority']>=5 and new['priority']<active['priority']:new=None
            if new:active=new
            if active:
                age=row-active['row'];remaining=active['end']-row
                s=bank[active['sid']-1];envelope=1.
                if active['shape']!='drum':
                    envelope*=min(1,remaining/(4 if channel==0 else 3))
                    if active['shape']=='outro':envelope*=max(0,1-age/(active['end']-active['row']))**1.5
                    if active['shape']=='rise':envelope*=.25+.75*age/(active['end']-active['row'])
                    if channel in (1,2,3) and intro<=row<intro+body:
                        k=bisect.bisect_right(kicks,row)-1
                        distance=row-kicks[k] if k>=0 else 100
                        floor=.57 if channel==1 else .25
                        envelope*=floor+(1-floor)*min(1,distance/(6 if style else 10))
                volume=round(min(64,s['volume']*active['gain']*envelope))
            else:volume=0
            if new:events[row,channel]=[active['sid'],active['pitch'],12,volume]
            elif volume!=previous_volume or row==2:events[row,channel]=[0,0,12,volume]
            previous_volume=volume
    # Stereo separation: centred bass/drums, opposite chord/echo sides. Only
    # ordinary pan/volume/tempo effects are used; no extra runtime DSP or voices.
    pans=(118,128,58,194,205,128,139,173) if style==0 else (128,128,68,188,204,128,146,179)
    for ch,pan in enumerate(pans):events[1,ch]=[0,0,8,pan]
    def command(row,fx,value):
        for ch in range(7,-1,-1):
            if (row,ch) not in events:
                events[row,ch]=[0,0,fx,value];return
        # Keep an existing sample attack when the opening row is fully occupied.
        for ch in (7,6,4,3,2,1,0,5):
            if events[row,ch][2] not in (8,15):
                events[row,ch][2:]=[fx,value];return
        raise AssertionError('no channel for tempo command')
    command(0,15,1)
    mapping=[];tempos=[];ms=0.;previous=-1
    for row in range(rows):
        local=row-intro
        bpm=max(32,min(255,round(clock.bpm(max(0,min(body-1,local)))*scale)))
        if trance:bpm=round(target*club_pulse/24)
        if bpm!=previous:command(row,15,bpm);tempos.append([row,bpm]);previous=bpm
        mapping.append((round(ms),round(clock.cs(local)) if 0<=local<body else -1))
        ms+=2500/bpm
    mapping.append((round(ms),-1))
    for ch in range(8):events[rows-1,ch]=[0,0,12,0]
    packer=runpy.run_path(str(Path(__file__).with_name('PackRows')))
    events,rows,mapping,speed=packer['pack'](events,rows,mapping)
    used=sorted({event[0] for event in events.values() if event[0]})
    assert len(used)<=31,(song['title'],len(used))
    remap={sid:i+1 for i,sid in enumerate(used)};selected=[bank[sid-1] for sid in used]
    title=(('TRANCE ' if trance else 'CHILL ' if style==0 else 'PC-POP ')+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'
    patterns=rows//64
    out+=bytes((patterns,0))+bytes(range(patterns)).ljust(128,b'\0')+b'8CHN'
    for row in range(rows):
        for channel in range(8):
            sid,pitch,fx,value=events.get((row,channel),(0,0,0,0));period=0
            if sid:
                s=bank[sid-1];period=round(s['period']*2**((s['base']-pitch)/12))
                assert 1<=period<=4095
                sid=remap[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',*point) for point in mapping)
    assert len(timing)<=65556
    meta=dict(title=song['title'],style=style+1,label=('Electronic Chillout','90s PC-Pop','Classical Instruments','Dance/Trance')[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,
        arrangement=TRANCE['FAMILIES'][family] if trance else FAMILIES[style][family],sections=sections,meter_map=clock.segments,
        bars=bars,rhythm=rhythm,phrase_rows=phrase_rows,lead_instrument=fixed_lead,
        palette=dict(lead=fixed_lead,bass=bass_name,pad=pad_kind,stab=stab_kind,counter=counter),
        estimated_key=dict(tonic=key,minor=minor),lead_preserved=True,
        backing='new syncopated bass, voiced seventh chords, sidechain volume envelopes, distinct drum kit, timed echoes')
    if trance:meta.update(dance_bpm=target,kick_pulse_rows=club_pulse)
    return bytes(out),timing,packer['metadata'](meta,speed)
