"""Background ambiences, generated per scene and crossfaded: the sound of the place the scene happens in.
Kept quiet on purpose: they sit under the voice and the music."""
import os
import numpy as np
import soundfile as sf
from scipy.signal import butter, sosfilt, resample_poly

SR = 48000
KINDS = ['none', 'room', 'office', 'studio', 'kitchen', 'cafe', 'beach', 'park', 'city', 'night', 'rain', 'booth']

def _f(kind, f, x, order=2):
    return sosfilt(butter(order, f, kind, fs=SR, output='sos'), x)

def _pink(rng, n):
    """Approximate pink noise (Voss-like via filtered white)."""
    w = rng.standard_normal(n)
    b = np.array([0.049922035, -0.095993537, 0.050612699, -0.004408786]); a = np.array([1, -2.494956002, 2.017265875, -0.522189400])
    from scipy.signal import lfilter
    return lfilter(b, a, w) * 6

def _brown(rng, n):
    x = np.cumsum(rng.standard_normal(n)); x -= _f('low', 2, x, 1)  # remove drift
    return x / (np.max(np.abs(x)) + 1e-9)

def _env(n, rate, rng, depth=.5, smooth=1.5):
    """Slow random amplitude movement."""
    k = max(2, int(n / SR * rate) + 2)
    pts = 1 - depth + depth * rng.random(k)
    e = np.interp(np.linspace(0, k - 1, n), np.arange(k), pts)
    return _f('low', smooth, e, 1)

def _sample(name):
    x, sr = sf.read(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sfx', name + '.wav'))
    x = x.mean(1) if x.ndim > 1 else x
    return resample_poly(x, SR, sr) if sr != SR else x

def _scatter(out, y, rate, rng, gain, pitch=(0.8, 1.25), pan=.6):
    """Drop a short sound at random times (Poisson), with small pitch and pan changes."""
    n = out.shape[1]; t = rng.exponential(1 / rate)
    while t * SR < n:
        r = rng.uniform(*pitch); idx = np.arange(0, len(y) - 1, r); z = np.interp(idx, np.arange(len(y)), y)
        i = int(t * SR); m = min(len(z), n - i); p = rng.uniform(-pan, pan); g = gain * rng.uniform(.5, 1)
        out[0, i:i + m] += z[:m] * g * np.cos((p + 1) * np.pi / 4) * 1.41
        out[1, i:i + m] += z[:m] * g * np.sin((p + 1) * np.pi / 4) * 1.41
        t += rng.exponential(1 / rate)

def _chirp(f0, f1, d, rng):
    t = np.arange(int(d * SR)) / SR
    f = np.linspace(f0, f1, len(t)) * (1 + .04 * np.sin(2 * np.pi * 30 * t))
    return np.sin(2 * np.pi * np.cumsum(f) / SR) * np.sin(np.pi * t / d) ** 2

def bed(kind, d, seed=0):
    """Stereo ambience of length d seconds."""
    rng = np.random.default_rng(seed); n = int(d * SR); out = np.zeros((2, n))
    if kind in ('none', None): return out
    st = lambda f: np.stack([f(), f()])
    # every place has a little room tone
    tone = st(lambda: _f('low', 500, _pink(rng, n))) * .05
    if kind in ('room', 'office', 'booth', 'studio', 'kitchen', 'cafe'): out += tone
    if kind == 'office':
        _scatter(out, _sample('click_002'), 4.0, rng, .05, (.7, 1.1))           # keyboard
        out += st(lambda: _f('band', [90, 130], rng.standard_normal(n))) * .01   # air conditioning hum
    elif kind == 'studio':
        out += st(lambda: _f('band', [150, 1800], _pink(rng, n))) * .05 * _env(n, .3, rng, .4)
    elif kind == 'booth':
        out *= .5
    elif kind == 'kitchen':
        sizzle = st(lambda: _f('band', [2500, 9000], rng.standard_normal(n) * (rng.random(n) < .02))) * .35
        out += sizzle * _env(n, .5, rng, .6)
        _scatter(out, _sample('glass_002'), .35, rng, .06, (.7, 1.3))           # cutlery and plates
    elif kind == 'cafe':
        murmur = np.zeros((2, n))
        for k in range(6):                                                       # several voices far away
            v = _f('band', [250, 2200], _pink(rng, n)); syl = _env(n, rng.uniform(3, 6), rng, .9, 8)
            murmur += np.stack([v * syl * rng.uniform(.4, 1), v * syl * rng.uniform(.4, 1)])
        out += _f('low', 1800, murmur) * .03
        _scatter(out, _sample('glass_002'), .5, rng, .05, (.8, 1.2))             # cups
    elif kind == 'beach':
        w = np.zeros((2, n)); t = np.arange(n) / SR
        for c in range(2):
            period = rng.uniform(6, 8.5); ph = rng.uniform(0, period)
            cyc = ((t + ph) % period) / period
            swell = np.where(cyc < .35, (cyc / .35) ** 2, np.exp(-(cyc - .35) * 5))
            noise = _pink(rng, n)
            w[c] = (_f('low', 900, noise) * .7 + _f('band', [1200, 6000], noise) * .35 * swell) * (.25 + swell)
        out += w * .18 + st(lambda: _f('low', 300, _pink(rng, n))) * .05
    elif kind == 'park':
        out += st(lambda: _f('band', [200, 1200], _pink(rng, n))) * .03 * _env(n, .25, rng, .7)   # breeze
        t = 0.3
        while t < d - .5:                                                        # small bird phrases
            i = int(t * SR); phrase = np.concatenate([_chirp(rng.uniform(2800, 4200), rng.uniform(3200, 5200), rng.uniform(.05, .11), rng) for _ in range(rng.integers(2, 6))])
            m = min(len(phrase), n - i); p = rng.uniform(-.8, .8)
            out[0, i:i + m] += phrase[:m] * .05 * (1 - p); out[1, i:i + m] += phrase[:m] * .05 * (1 + p)
            t += rng.uniform(.8, 2.6)
    elif kind == 'city':
        out += st(lambda: _f('low', 220, _brown(rng, n))) * .07
        t = rng.uniform(.5, 2)
        while t < d:                                                              # cars passing far away
            dur = rng.uniform(2.5, 4); m = min(int(dur * SR), n - int(t * SR))
            if m <= 0: break
            x = _f('band', [150, 900], _pink(rng, m)) * np.sin(np.pi * np.arange(m) / m) ** 2 * .06
            p = np.linspace(-.7, .7, m) * rng.choice([-1, 1]); i = int(t * SR)
            out[0, i:i + m] += x * (1 - p); out[1, i:i + m] += x * (1 + p)
            t += rng.uniform(2, 5)
    elif kind == 'night':
        out += st(lambda: _f('low', 400, _pink(rng, n))) * .03
        for k in range(3):                                                        # crickets
            f0 = rng.uniform(4200, 5200); t = rng.uniform(0, 1); p = rng.uniform(-.7, .7)
            while t < d:
                for j in range(3):
                    i = int((t + j * .05) * SR); c = _chirp(f0, f0, .03, rng); m = min(len(c), n - i)
                    if m > 0: out[0, i:i + m] += c[:m] * .012 * (1 - p); out[1, i:i + m] += c[:m] * .012 * (1 + p)
                t += rng.uniform(.6, 1.1)
    elif kind == 'rain':
        out += st(lambda: _f('band', [800, 9000], _pink(rng, n))) * .07 + st(lambda: _f('low', 300, _pink(rng, n))) * .04
        _scatter(out, _sample('click_002'), 12, rng, .03, (.5, 1.5), .9)         # drops
    return out

def build(scenes, total, out_path, seed=5):
    """scenes: [{start, dur, ambience}]. Crossfades 0.6 s between places."""
    n = int(total * SR); mix = np.zeros((2, n)); fade = int(.6 * SR)
    for k, s in enumerate(scenes):
        kind = s.get('ambience') or 'none'
        if kind == 'none': continue
        a = max(0, int((s['start'] - .3) * SR)); b = min(n, int((s['start'] + s['dur'] + .3) * SR))
        y = bed(kind, (b - a) / SR + .01, seed + k)[:, :b - a]
        if y.shape[1] < b - a: y = np.pad(y, ((0, 0), (0, b - a - y.shape[1])))
        e = np.ones(b - a); f = min(fade, (b - a) // 2)
        e[:f] = np.linspace(0, 1, f); e[-f:] = np.linspace(1, 0, f)
        mix[:, a:b] += y * e
    sf.write(out_path, mix.T.astype(np.float32), SR)
    return {'file': out_path, 'scenes': sum(1 for s in scenes if (s.get('ambience') or 'none') != 'none')}
