"""Original, offline-synthesised club/pop instruments. No downloaded audio.

These are baked signed 8-bit PCM samples for ordinary eight-channel QTM MODs.
The existing SampleBank and all recorded classical instruments are untouched.
"""
import math
import numpy as np
from scipy import signal

PERIOD = 200
RATE = 3546894.6 / PERIOD

def build_bank():
    rng = np.random.default_rng(263023)
    bank = []
    def t(n): return np.arange(round(n * RATE)) / RATE
    def filt(x, hz, high=False):
        return signal.sosfilt(signal.butter(2, hz, fs=RATE,
            btype='highpass' if high else 'lowpass', output='sos'), x)
    def add(name, x, base=60, volume=48, loop=None):
        x = np.array(x, float, copy=True)
        x -= np.mean(x)
        x *= .91 / max(1e-9, np.max(np.abs(x)))
        attack = min(len(x), round(.002 * RATE))
        x[:attack] *= np.linspace(0, 1, attack)
        start = length = 0
        if loop:
            start, end = (round(v * RATE) // 2 * 2 for v in loop)
            cross = round(.055 * RATE) // 2 * 2
            x[end-cross:end] = (x[end-cross:end] * np.linspace(1, 0, cross)
                + x[start-cross:start] * np.linspace(0, 1, cross))
            x = x[:end]; length = end - start
        else:
            n = min(len(x), round(.04 * RATE))
            x[-n:] *= np.linspace(1, 0, n)
        pcm = np.round(x * 127).astype('i1').tobytes()
        pcm += b'\0' * (len(pcm) % 2)
        assert len(name) <= 22 and len(pcm) <= 131070
        bank.append(dict(name=name, base=base, period=PERIOD, volume=volume,
            loop_start=start, loop_length=length, pcm=pcm,
            origin='Original algorithmic synthesis, OakAcorn Software / OpenAI Codex, 02-Nov-2026'))
    def osc(tt, f, bright=.6, detune=.002, phase=0):
        return sum(np.sin(2*np.pi*f*k*(1+d)*tt + phase + j*.7)
            * np.exp(-k*bright) / k for j,d in enumerate((-detune,0,detune))
            for k in range(1,12) if f*k < RATE*.44)
    # Round, reverberant-feeling lead timbres versus brighter pop hooks.
    tt=t(1.8);f=523.2511306
    for name,kind in [('Haze Keys',0),('Poolside Pluck',1),('Vapour Lead',2),
                      ('Prism Hook',3),('Silicon Hook',4),('Tropic Mallet',5)]:
        if kind==0:
            x=(np.sin(2*np.pi*f*tt + .9*np.sin(2*np.pi*f*tt)*np.exp(-tt/.16))
               + .17*np.sin(2*np.pi*f*2*tt))*np.exp(-tt/.85)
        elif kind==1:
            x=osc(tt,f,.38,.003)*np.exp(-tt/.32)
            x+=.18*np.sin(2*np.pi*f*2*tt)*np.exp(-tt/.65)
        elif kind==2:
            x=osc(tt,f,.8,.004)*(.7+.3*np.sin(tt*3.3)**2)*np.minimum(1,tt/.025)
        elif kind==3:
            x=osc(tt,f,.18,.0045)*(.45+.55*np.exp(-tt/.22))
        elif kind==4:
            x=(np.sin(2*np.pi*f*tt + 2.2*np.sin(2*np.pi*f*tt)*np.exp(-tt/.28))
                + .25*osc(tt,f,.3,.001))*np.exp(-tt/.9)
        else:
            x=sum(a*np.sin(2*np.pi*f*k*tt)*np.exp(-tt/d)
                  for k,a,d in [(1,1,.75),(2,.25,.25),(3.01,.08,.15)])
        # Short diffused reflections are baked in; tempo-synchronised echoes
        # are separate tracker events, so they follow every tempo change.
        dry=x.copy()
        for seconds,gain in [(.043,.12),(.079,.09),(.127,.055)]:
            n=round(seconds*RATE);x[n:]+=dry[:-n]*gain
        add(name,x,72,45 if kind<3 else 47, (.65,1.6) if kind in (2,3) else None)
    # Eight new full-song lead palettes. Original offline synthesis; stable
    # sustained loop tails retain identity during long carol notes.
    for name,kind in [('Velour EP',0),('Dub Organ',1),('Nylon Mist',2),('Aurora Glass',3),
                      ('Wide Saw',4),('FM Neon',5),('Marimba Air',6),('Vowel Cloud',7)]:
        tt=t(2.7);f=523.2511306;phase=2*np.pi*f*tt
        if kind==0:
            x=(np.sin(phase+1.9*np.sin(phase)*np.exp(-tt/.16))
               +.16*np.sin(phase*3)*np.exp(-tt/.26))*(.24+.76*np.exp(-tt/.8))
            x*=1+.07*np.sin(tt*math.tau*4.1)
        elif kind==1:
            x=sum(g*np.sin(phase*h) for h,g in [(1,1),(2,.38),(3,.23),(4,.07),(6,.09)])
            x*=np.minimum(1,tt/.009)*(1+.04*np.sin(tt*math.tau*5))
        elif kind==2:
            x=sum(np.sin(phase*h+.05*h)*(.35+.65*np.exp(-tt*h*.8))/h**1.7 for h in range(1,10))
            x+=filt(rng.normal(size=len(tt)),1500)*.09*np.exp(-tt/.012)
        elif kind==3:
            x=(np.sin(phase+.5*np.sin(phase*3)*np.exp(-tt/.3))+.15*np.sin(phase*2.01)*np.exp(-tt/.5))
            x*=.30+.70*np.exp(-tt/.9)
        elif kind==4:
            x=osc(tt,f,.17,.006)*(.65+.35*np.exp(-tt/.18))
        elif kind==5:
            x=np.sin(phase+1.8*np.sin(phase*2)*(.25+.75*np.exp(-tt/.25)))
            x+=.16*np.sin(phase*.998);x*=.46+.54*np.exp(-tt/.85)
        elif kind==6:
            x=sum(g*np.sin(phase*h)*(.15+.85*np.exp(-tt/d)) for h,g,d in [(1,1,.65),(2,.25,.20),(4,.07,.08)])
        else:
            x=sum(np.sin(phase*h)*(.08+sum(g*np.exp(-((f*h-centre)/width)**2) for centre,width,g in [(750,160,.75),(1250,260,.6),(2500,500,.18)]))/h for h in range(1,14))
            x*=np.minimum(1,tt/.025)*(1+.05*np.sin(tt*math.tau*4.7))
        dry=x.copy()
        for seconds,gain in [(.031,.10),(.061,.07),(.101,.045),(.149,.025)]:
            n=round(seconds*RATE);x[n:]+=dry[:-n]*gain
        add(name,x,72,44 if kind<4 else 46,(1.65,2.55))
    # Club bass has a clean fundamental; pop bass has more upper harmonics
    # and a short filter-like attack. Arrangement gates supply the rhythm.
    tt=t(1.45);f=65.4063913
    for name,k in [('Round Sub',0),('Deep Rubber Bass',1),('Pop Pulse Bass',2),('FM Bounce Bass',3)]:
        if k==0:x=np.sin(2*np.pi*f*tt)+.14*np.sin(4*np.pi*f*tt)
        elif k==1:x=np.sin(2*np.pi*f*tt)+osc(tt,f,.7,.001)*(.35+.5*np.exp(-tt/.06))
        elif k==2:x=np.tanh((np.sin(2*np.pi*f*tt)+.35*np.sin(4*np.pi*f*tt)) * 1.4)
        else:x=np.sin(2*np.pi*f*tt+.8*np.sin(4*np.pi*f*tt)*np.exp(-tt/.12))
        add(name,x*np.minimum(1,tt/.006),36,54,(.65,1.35))
    # Extended harmony has actual simultaneous chord tones in one channel.
    # The fifth/seventh voice is quieter, leaving the carol melody prominent.
    chords={'Maj7':[(0,1),(4,.65),(7,.48),(11,.18)],
            'Min7':[(0,1),(3,.65),(7,.48),(10,.22)],
            'Dom7':[(0,1),(4,.65),(7,.48),(10,.20)],
            'Dim':[(0,1),(3,.65),(6,.48)]}
    for quality,tones in chords.items():
        for kind in ('Cloud','House','Pop','Silk','Felt'):
            tt=t(2.35 if kind in ('Cloud','Silk') else 1.1)
            x=sum(g*osc(tt,261.6255653*2**(n/12),
                       .85 if kind=='Cloud' else .30 if kind=='House' else .17,
                       .0025 if kind!='Pop' else .004)
                  for n,g in tones)
            if kind=='Silk':
                x=sum(g*(np.sin(2*np.pi*261.6255653*2**(n/12)*tt)+.2*osc(tt,261.6255653*2**(n/12),1.1,.003)) for n,g in tones)
                x*=np.minimum(1,tt/.10)
            elif kind=='Felt':
                x=sum(g*np.sin(2*np.pi*261.6255653*2**(n/12)*tt+.65*np.sin(2*np.pi*261.6255653*2**(n/12)*tt)*np.exp(-tt/.12)) for n,g in tones)
                x*=np.exp(-tt/.44)
            elif kind=='Cloud':x*=np.minimum(1,tt/.055)
            else:x*=np.exp(-tt/(.24 if kind=='House' else .32))
            add(kind+' '+quality,x,60,30 if kind in ('Cloud','Silk') else 38,
                (.8,2.2) if kind in ('Cloud','Silk') else None)
    # Two completely different drum kits, plus light percussion and transitions.
    for name,k in [('Club Kick',0),('Pop Punch Kick',1)]:
        tt=t(.44);frequency=(43 if k==0 else 51)+(120 if k==0 else 180)*np.exp(-tt/.014)
        x=np.sin(2*np.pi*np.cumsum(frequency)/RATE)*np.exp(-tt/(.13 if k==0 else .095))
        x+=rng.normal(size=len(tt))*.10*np.exp(-tt/.0035)
        add(name,np.tanh(x*(1.2 if k==0 else 1.8)),60,62)
    for name,k in [('Dust Rim',0),('Club Clap',1),('Pop Snap',2),('Pop Snare',3)]:
        tt=t(.30);noise=filt(rng.normal(size=len(tt)),1000 if k<2 else 1800,True)
        if k==0:x=(np.sin(2*np.pi*440*tt)+.5*np.sin(2*np.pi*770*tt))*np.exp(-tt/.022)+.14*noise*np.exp(-tt/.035)
        elif k in (1,2):
            envelope=sum(np.exp(-np.maximum(0,tt-a)/.009)*(tt>=a) for a in (0,.011,.024))
            x=noise*(envelope+.35*np.exp(-tt/(.07 if k==1 else .045)))
            if k==2:x+=.15*np.sin(2*np.pi*240*tt)*np.exp(-tt/.035)
        else:x=noise*np.exp(-tt/.065)+.42*np.sin(2*np.pi*185*tt)*np.exp(-tt/.045)
        add(name,x,60,(40,42,45,47)[k])
    for name,duration,decay,vol in [('Club Closed',.10,.018,24),('Club Open',.35,.075,29),
                                     ('Pop Closed',.09,.013,27),('Pop Open',.29,.06,31),
                                     ('Soft Shaker',.16,.032,22)]:
        tt=t(duration);x=filt(rng.normal(size=len(tt)),3600,True)*np.exp(-tt/decay)
        add(name,x,60,vol)
    tt=t(1.8);x=filt(rng.normal(size=len(tt)),2400,True)*np.minimum(1,tt/.8)**2
    add('Air Lift',x,60,23)
    tt=t(1.4);x=filt(rng.normal(size=len(tt)),2300,True)*np.exp(-tt/.31)
    add('Bright Splash',x,60,28)
    return bank
