"""Music played on real recorded instruments, arranged to the length of the video.
Instruments: tonejs-instruments (piano, acoustic guitar, electric bass; CC BY 3.0, Nicholaus Brosowsky)
Drums and percussion: Virtuosity Drums (CC0, sfzinstruments). Samples are downloaded once into the samples folder."""
import os, subprocess, urllib.request
import numpy as np
from scipy.signal import butter, sosfilt, fftconvolve

SR = 48000
TONEJS = 'https://raw.githubusercontent.com/nbrosowsky/tonejs-instruments/master/samples/{inst}/{note}.mp3'
DRUMS = 'https://raw.githubusercontent.com/sfzinstruments/virtuosity_drums/master/{path}'
NOTES = {   # notes recorded for each instrument (the closest one is re-pitched)
  'piano': [n + str(o) for o in range(1, 8) for n in ['C', 'Cs', 'D', 'Ds', 'E', 'F', 'Fs', 'G', 'Gs', 'A', 'As', 'B']],
  'guitar-acoustic': 'A2 A3 A4 As2 As3 As4 B2 B3 B4 C3 C4 C5 Cs3 Cs4 Cs5 D2 D3 D4 D5 Ds2 Ds3 Ds4 E2 E3 E4 F2 F3 F4 Fs2 Fs3 Fs4 G2 G3 G4 Gs2 Gs3 Gs4'.split(),
  'bass-electric': 'As1 As2 As3 As4 Cs1 Cs2 Cs3 Cs4 Cs5 E1 E2 E3 E4 G1 G2 G3 G4'.split(),
}
KIT = {
  'kick': ['Samples/mid/kick/mid_kick_snoff_vl3_rr1.flac', 'Samples/mid/kick/mid_kick_snoff_vl3_rr2.flac', 'Samples/mid/kick/mid_kick_snoff_vl4_rr1.flac'],
  'snare': ['Samples/mid/snare/mid_snare_center_vl9.flac', 'Samples/mid/snare/mid_snare_center_vl12.flac', 'Samples/mid/snare/mid_snare_center_vl15.flac'],
  'hat': ['Samples/mid/hh/mid_hh_closed_vl2_rr1.flac', 'Samples/mid/hh/mid_hh_closed_vl4_rr1.flac'],
  'open': ['Samples/mid/hh/mid_hh_open_vl1_rr1.flac'],
  'crash': ['Samples/mid/crash/mid_crash_crash_vl1_rr1.flac'],
  'shaker': ['Samples/perc/close/shaker/LShaker_Shake1D_rr1_Close.wav', 'Samples/perc/close/shaker/LShaker_Shake1U_rr1_Close.wav',
             'Samples/perc/close/shaker/LShaker_Shake1D_rr2_Close.wav', 'Samples/perc/close/shaker/LShaker_Shake1U_rr2_Close.wav'],
  'tamb': ['Samples/perc/close/tambourine/Tamb1_Shake_rr1_Close.wav', 'Samples/perc/close/tambourine/Tamb1_Shake_rr10_Close.wav'],
}
PC = {'C': 0, 'Cs': 1, 'D': 2, 'Ds': 3, 'E': 4, 'F': 5, 'Fs': 6, 'G': 7, 'Gs': 8, 'A': 9, 'As': 10, 'B': 11}
midi_of = lambda n: 12 * (int(n[-1]) + 1) + PC[n[:-1]]

def decode(f, stereo=False):
    raw = subprocess.run(['ffmpeg', '-loglevel', 'error', '-i', f, '-f', 'f32le', '-ac', '2' if stereo else '1', '-ar', str(SR), '-'], capture_output=True, check=True).stdout
    x = np.frombuffer(raw, np.float32).astype(np.float64)
    return x.reshape(-1, 2).T if stereo else x

class Bank:
    def __init__(self, sdir):
        self.dir = os.path.join(sdir, 'real'); self.cache = {}
    def _get(self, url, local):
        f = os.path.join(self.dir, local)
        if not os.path.exists(f):
            os.makedirs(os.path.dirname(f), exist_ok=True)
            urllib.request.urlretrieve(url, f + '.part'); os.replace(f + '.part', f)
        return f
    def note(self, inst, m):
        key = (inst, m)
        if key in self.cache: return self.cache[key]
        src = min(NOTES[inst], key=lambda n: (abs(midi_of(n) - m), midi_of(n) < m))
        x = decode(self._get(TONEJS.format(inst=inst, note=src), f'{inst}/{src}.mp3'))
        i = int(np.argmax(np.abs(x) > .003)); x = x[max(0, i - 24):]
        d = m - midi_of(src)
        if d:                                                            # re-pitch by resampling (at most a few semitones)
            r = 2 ** (d / 12); idx = np.arange(0, len(x) - 1, r)
            x = np.interp(idx, np.arange(len(x)), x)
        self.cache[key] = x
        return x
    def drum(self, kind, k=0):
        lst = KIT[kind]; path = lst[k % len(lst)]
        key = ('kit', path)
        if key not in self.cache:
            x = decode(self._get(DRUMS.format(path=path.replace(' ', '%20')), 'kit/' + os.path.basename(path)))
            i = int(np.argmax(np.abs(x) > .004)); self.cache[key] = x[max(0, i - 24):]
        return self.cache[key]

# chord progressions (root for the bass, voicing for guitar/piano), in C major: I V vi IV
PROG = {
  'pop':      [(36, [48, 52, 55, 60, 64]), (43, [47, 50, 55, 59, 62]), (45, [45, 52, 57, 60, 64]), (41, [48, 53, 57, 60, 65])],
  'acoustic': [(43, [43, 50, 55, 59, 62]), (40, [40, 47, 52, 55, 59]), (36, [48, 52, 55, 60, 64]), (38, [50, 54, 57, 62, 66])],
}

def build(mood, D, sdir, seed=11):
    """Arranged track: intro, groove, a lift in the middle, short outro that lands on the last chord."""
    bank = Bank(sdir); rng = np.random.default_rng(seed)
    bpm = 112 if mood == 'pop' else 92
    BEAT = 60 / bpm; BAR = 4 * BEAT; L = int((D + 4) * SR)
    bus = {k: np.zeros((2, L)) for k in ('gtr', 'keys', 'bass', 'kit', 'perc')}
    def put(b, y, t0, pan=0., g=1.):
        t0 += rng.normal(0, .004)                                       # human timing
        i = int(round(t0 * SR)); n = min(len(y), L - i)
        if n <= 0 or i < 0: return
        bus[b][0, i:i + n] += y[:n] * g * np.cos((pan + 1) * np.pi / 4) * 1.414
        bus[b][1, i:i + n] += y[:n] * g * np.sin((pan + 1) * np.pi / 4) * 1.414
    def play(b, inst, m, t0, dur, vel, pan=0., rel=.25):
        x = bank.note(inst, m); n = min(len(x), int((dur + rel) * SR)); y = x[:n].copy()
        h = max(0, n - int(rel * SR)); y[h:] *= np.linspace(1, 0, n - h) ** 2
        put(b, y, t0, pan, vel * rng.uniform(.88, 1.0))
    def strum(t0, voic, dur, vel, up=False):
        order = voic[::-1] if up else voic
        for j, m in enumerate(order): play('gtr', 'guitar-acoustic', m, t0 + j * (.009 if up else .013), dur, vel * (.75 if up else 1) * (1 - .05 * j), -.35 + .14 * j, rel=.12)
    hit = lambda kind, t, g, pan=0., k=None: put('kit' if kind not in ('shaker', 'tamb') else 'perc', bank.drum(kind, rng.integers(9) if k is None else k), t, pan, g * rng.uniform(.9, 1.0))

    bars = int(np.ceil(D / BAR))
    last = bars - 1
    for bar in range(bars + 1):
        T = bar * BAR
        if T > D + .1: break
        root, voic = PROG[mood][bar % 4]
        final = bar >= last
        intro = bar < 2
        lift = bars >= 8 and bars // 2 <= bar < bars // 2 + 2               # a short breakdown in the middle
        if final:                                                          # land on the tonic and let it ring
            r0, v0 = PROG[mood][0]
            strum(T, v0, BAR * 1.6, .9); play('keys', 'piano', v0[-1] + 12, T, BAR * 1.6, .25, .25, rel=1.2)
            play('bass', 'bass-electric', max(28, r0 - 12 if r0 > 40 else r0), T, BAR * 1.4, .8, rel=.8)
            if mood == 'pop': hit('kick', T, .9); hit('crash', T, .32, .3, 0)
            break
        if mood == 'pop':
            # guitar: D . D U . U D U
            pat = [(0, False), (1, False), (1.5, True), (2.5, True), (3, False), (3.5, True)]
            for b8, up in pat: strum(T + b8 * BEAT, voic, BEAT * (1.2 if not up else .7), .55 if not lift else .38, up)
            if not intro:
                for k8 in range(8):                                        # piano off-beat stabs, light
                    if k8 % 2: [play('keys', 'piano', m + 12, T + k8 * BEAT / 2, BEAT * .35, .10, .3) for m in voic[2:5]]
            if not intro and not lift:
                for b8 in (0, 1.5, 2, 3.5): play('bass', 'bass-electric', root - 12 if root > 40 else root, T + b8 * BEAT, BEAT * .45, .75, rel=.08)
                hit('kick', T, .85); hit('kick', T + 1.5 * BEAT, .55); hit('kick', T + 2 * BEAT, .8)
                hit('snare', T + BEAT, .42, .05); hit('snare', T + 3 * BEAT, .45, .05)
                for k8 in range(8): hit('hat', T + k8 * BEAT / 2, .26 if k8 % 2 else .34, .3, k8 % 2)
                hit('tamb', T + BEAT, .12, -.4); hit('tamb', T + 3 * BEAT, .12, -.4)
                if bar % 8 == 7: hit('open', T + 3.5 * BEAT, .12, .3)
                if bar == 2 or (lift is False and bars >= 8 and bar == bars // 2 + 2): hit('crash', T, .28, .35, 0)
            for k16 in range(16): hit('shaker', T + k16 * BEAT / 4, (.07 if k16 % 2 else .1) * (.6 if intro else 1), -.5, k16 % 4)
        else:  # acoustic: fingerpicked guitar, piano, shaker
            pick = [0, 2, 3, 4, 1, 3, 2, 4]
            for k8, j in enumerate(pick): play('gtr', 'guitar-acoustic', voic[j], T + k8 * BEAT / 2, BEAT * 1.4, .45, -.3 + .12 * j, rel=.3)
            if not intro:
                play('keys', 'piano', voic[-1] + 12, T, BAR * .9, .16, .3, rel=.8)
                play('bass', 'bass-electric', root - 12 if root > 40 else root, T, BAR * .9, .55, rel=.4)
                for k8 in range(8): hit('shaker', T + k8 * BEAT / 2, .07 if k8 % 2 else .1, -.4, k8 % 4)

    # mix: gentle EQ per bus, a little room, glue compression, limiter
    lp = lambda x, f: sosfilt(butter(2, f, 'low', fs=SR, output='sos'), x)
    hp = lambda x, f: sosfilt(butter(2, f, 'high', fs=SR, output='sos'), x)
    bp = lambda x, a, b: sosfilt(butter(2, [a, b], 'band', fs=SR, output='sos'), x)
    gtr = np.stack([hp(bus['gtr'][c], 170) - .35 * bp(bus['gtr'][c], 200, 450) for c in range(2)])
    keys = np.stack([hp(bus['keys'][c], 250) for c in range(2)])
    bass = np.stack([lp(bus['bass'][c], 2500) for c in range(2)])
    kit = bus['kit']; perc = np.stack([hp(bus['perc'][c], 300) for c in range(2)])
    kit = np.stack([kit[c] - .3 * bp(kit[c], 250, 600) for c in range(2)])
    mix = gtr * .85 + keys * .8 + bass * .8 + kit * .9 + perc * 1.1
    mix = np.stack([mix[c] - .3 * bp(mix[c], 150, 450) + .7 * bp(mix[c], 2000, 8000) + .8 * hp(mix[c], 8000) for c in range(2)])   # tilt: less mud, more presence and air
    t = np.arange(int(1.4 * SR)) / SR; ir = rng.standard_normal((2, len(t))) * np.exp(-t * 4.2); ir[:, :int(.012 * SR)] = 0
    send = gtr * .5 + keys + perc * .3
    mix = mix + np.stack([fftconvolve(send[c], ir[c])[:L] for c in range(2)]) * .006
    env = np.sqrt(sosfilt(butter(1, 6, 'low', fs=SR, output='sos'), (mix ** 2).mean(0)) + 1e-12)
    thr = np.percentile(env, 70); g = np.minimum(1, (thr / env) ** .3)          # ~2:1 glue
    mix = mix * g
    mix = mix[:, :int(D * SR)]
    return np.tanh(mix / (np.percentile(np.abs(mix), 99.95) + 1e-9) * 1.1) * .95
