"""Sequence Dance/Trance against the existing carol melody and harmony.
The kick and offbeat bass share one uninterrupted clock across phrase changes.
"""
LEADS = ('Halo Supersaw','Ionic FM','Prism Lead','Solar Sync')
FAMILIES = ('Uplifting trance','Progressive trance','Peak-time trance','Driving psytrance')
TEMPI = (144,148,152,156)

def sequence(note, harmony, section, sections, family, intro, body, rows, pulse, pickup):
    # Anchor to the first full measure so a short pickup leads into a downbeat.
    anchor = intro + pickup
    first = anchor % pulse
    starts = list(range(first, rows-1, pulse))
    if first:
        starts.insert(0, 0)
    bass_name = ('Rolling Sub','Phase Bass','Rolling Sub','Phase Bass')[family]
    rhythm = []
    for i,start in enumerate(starts):
        stop = starts[i+1] if i+1 < len(starts) else rows-1
        length = stop-start
        beat = (start-anchor)//pulse
        role,energy = section(max(0,min(body-1,start-intro)))
        root,chord,quality,tones = harmony(start-intro)
        note(start,5,'Vector Kick',length=min(length, pulse*.84),gain=.96,shape='drum')
        rhythm.append(dict(row=start,kind='kick'))
        if beat%2:
            note(start,6,'Photon Clap',length=min(length,pulse*.75),gain=.85,shape='drum')
        note(start,2,'Aurora '+quality,chord,length,.66*energy,'pad')
        # The different bass gates and arp contours give each palette a groove.
        bass_slots=((2,), (2,3), (1,2), (1,2,3))[family]
        arp_pattern=((0,1,2,1),(0,2,1,3),(2,1,0,1),(0,1,2,3))[family]
        for slot in range(4):
            offset=round(slot*pulse/4)
            if offset>=length:break
            row=start+offset
            bass,chord,quality,tones=harmony(row-intro)
            if slot in bass_slots:
                pitch=bass+(12 if family==2 and slot==2 and beat%4==3 else 0)
                note(row,1,bass_name,pitch,min(pulse*.23,length-offset),.97,'bass')
            if slot%2==0 or (slot==3 and role in ('build','hook','finale')):
                name='Ion Open' if slot==2 else 'Ion Closed'
                note(row,7,name,length=min(pulse*.23,length-offset),
                     gain=.72 if slot==2 else .40,shape='drum')
            if slot in (1,3) or role in ('build','hook','finale'):
                degree=arp_pattern[(beat+slot)%4]
                note(row,3,'Laser Arp',chord+12+tones[degree],
                     min(pulse*.20,length-offset),(.56 if slot%2 else .34)*energy,'stab')
    for sec in sections:
        if sec['section'] in ('build','hook') and sec['row']>pulse:
            note(sec['row']-pulse,4,'Air Lift',length=pulse,gain=.64,shape='rise',priority=5)
    return rhythm
