"""Tsiky audio helper. Usage: python3 tsiky_audio.py <command> <job.json>
Commands:
  voices   -> list available TTS voices (prints JSON)
  tts      -> synthesize one wav per line, shaped by its tone     {lines:[{id,text,tone}], voice, speed, expressiveness, outDir, modelDir}
  analyze  -> analyse a user recording into a clean wav + envelope {input, out}
  music    -> build a music bed that ducks under the voice     {mood, duration, voice:[{start,dur}], out, samplesDir}
  mix      -> mix voice lines + music into one track (wav + mp3) {voice:[{file,start}], music, duration, out, mp3}
Every command prints a JSON result on stdout."""
import sys, os, re, json, subprocess, urllib.request
import numpy as np, soundfile as sf
from scipy.signal import butter, sosfilt, fftconvolve, resample_poly

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from voicefx import fx

def envelope(s, sr):
    """50 fps RMS envelope (mouth opening) and normalised zero-crossing rate (mouth width)."""
    hop = sr // 50; env, zcr = [], []
    for i in range(0, len(s), hop):
        fr = s[i:i + hop]
        env.append(float(np.sqrt(np.mean(fr ** 2))) if len(fr) else 0.)
        zcr.append(float(np.mean(np.abs(np.diff(np.sign(fr)))) / 2) if len(fr) > 1 else 0.)
    z = np.array(zcr); lo, hi = np.percentile(z, 10), np.percentile(z, 90)
    z = np.clip((z - lo) / (hi - lo + 1e-9), 0, 1)
    return [round(e, 4) for e in env], [round(float(v), 3) for v in z]

# ------------------------------------------------------------------ TTS (Kokoro, local)
VOICES = {
  'fr-female':        {'mix': [('ff_siwis', 1.0)], 'lang': 'fr-fr', 'label': 'French, female'},
  'fr-female-warm':   {'mix': [('ff_siwis', .8), ('af_heart', .2)], 'lang': 'fr-fr', 'label': 'French, female, warmer'},
  'fr-female-soft':   {'mix': [('ff_siwis', .7), ('bf_emma', .3)], 'lang': 'fr-fr', 'label': 'French, female, softer'},
  'en-female':        {'mix': [('af_heart', .6), ('af_bella', .4)], 'lang': 'en-us', 'label': 'English (US), female'},
  'en-female-soft':   {'mix': [('af_heart', .5), ('af_nicole', .5)], 'lang': 'en-us', 'label': 'English (US), female, softer'},
  'en-female-uk':     {'mix': [('bf_emma', .7), ('bf_isabella', .3)], 'lang': 'en-gb', 'label': 'English (UK), female'},
  'en-male':          {'mix': [('am_michael', .6), ('am_adam', .4)], 'lang': 'en-us', 'label': 'English (US), male'},
}

def kokoro(model_dir):
    from kokoro_onnx import Kokoro
    return Kokoro(os.path.join(model_dir, 'kokoro-v1.0.onnx'), os.path.join(model_dir, 'voices-v1.0.bin'))

def breath(rng, sr, d=.22):
    n = int(d * sr); t = np.arange(n) / sr
    b = sosfilt(butter(2, [400, 2400], 'band', fs=sr, output='sos'), rng.standard_normal(n))
    return (b * np.sin(np.pi * t / d) ** 2 * .012).astype(np.float32)

# Delivery per tone. speed: pace, st: pitch (semitones), db: energy, pause: pause length, breath: breath odds,
# vary: pitch movement between phrases, lift: first phrase lifted, end: last phrase up (+) or down (-), blend: timbre nudge
TONES = {
  'neutral':   dict(speed=1.00, st=0.0,  db=0,  pause=1.00, breath=.50, vary=.35, lift=0.0, end=-.4, blend={}),
  'warm':      dict(speed=.97,  st=-.3,  db=0,  pause=1.10, breath=.60, vary=.50, lift=.3,  end=-.5, blend={'af_heart': .15}),
  'excited':   dict(speed=1.10, st=1.6,  db=2,  pause=.75,  breath=.30, vary=.90, lift=1.0, end=.3,  blend={'af_bella': .22}),
  'calm':      dict(speed=.90,  st=-.8,  db=-2, pause=1.35, breath=.70, vary=.25, lift=0.0, end=-.6, blend={'af_nicole': .25}),
  'serious':   dict(speed=.95,  st=-1.2, db=1,  pause=1.15, breath=.30, vary=.20, lift=0.0, end=-.9, blend={'af_sarah': .15}),
  'playful':   dict(speed=1.06, st=1.0,  db=1,  pause=.85,  breath=.40, vary=1.3, lift=.5,  end=.4,  blend={'af_bella': .15}),
  'curious':   dict(speed=1.00, st=.6,   db=0,  pause=1.00, breath=.50, vary=.60, lift=0.0, end=1.3, blend={}),
  'surprised': dict(speed=1.04, st=2.0,  db=2,  pause=.90,  breath=.30, vary=.80, lift=1.6, end=0.0, blend={}),
  'confident': dict(speed=.98,  st=-.4,  db=1.5,pause=1.00, breath=.35, vary=.35, lift=.2,  end=-.7, blend={'af_sarah': .10}),
  'sad':       dict(speed=.88,  st=-1.6, db=-3, pause=1.40, breath=.80, vary=.20, lift=0.0, end=-1.0,blend={'af_nicole': .20}),
}

def shift(s, sr, semis):
    """Pitch shift with formants kept (no chipmunk), same length."""
    if abs(semis) < .05 or len(s) < sr // 20: return s
    r = subprocess.run(['ffmpeg', '-loglevel', 'error', '-f', 'f32le', '-ar', str(sr), '-ac', '1', '-i', '-',
                        '-af', f'rubberband=pitch={2 ** (semis / 12):.5f}:formant=preserved:pitchq=quality', '-f', 'f32le', '-'],
                       input=np.asarray(s, np.float32).tobytes(), capture_output=True)
    y = np.frombuffer(r.stdout, np.float32)
    return y if len(y) else s

def trim(s):
    s = np.asarray(s, np.float32); nz = np.where(np.abs(s) > .008)[0]
    return s[max(0, nz[0] - 300): nz[-1] + 600] if len(nz) else s

def speak(k, text, style, lang, base, seed, tone='neutral', amount=.8):
    """Phrase by phrase, shaped by the tone: pace, pitch, energy, pauses, breaths and phrase intonation.
    Markup: *word* stresses a word, "..." adds a hesitation."""
    rng = np.random.default_rng(seed); sr = 24000
    T = TONES.get(tone, TONES['neutral']); a = amount
    lerp = lambda neutral, v: neutral + (v - neutral) * a
    parts = [p.strip() for p in re.split(r'(?<=[,.?!:…;—])\s+', text.replace('...', '…')) if p.strip()]
    out = []
    for i, p in enumerate(parts):
        last = i == len(parts) - 1
        sp = base * lerp(1, T['speed']) * (1.0 + .05 * np.sin(i * 1.7 + seed))
        if p.endswith('?'): sp *= .96
        st = lerp(0, T['st']) + lerp(0, T['vary']) * np.sin(i * 2.3 + seed) * .8
        if i == 0: st += lerp(0, T['lift'])
        if last and len(parts) > 1: st += lerp(0, T['end'])
        if p.endswith('?'): st += .8 * a
        if p.endswith('!'): st += .6 * a
        # stressed words are spoken on their own: a touch slower, higher and louder
        segs = re.split(r'(\*[^*]+\*)', p)
        chunk = []
        for sg in segs:
            if not sg.strip(): continue
            emph = sg.startswith('*') and sg.endswith('*')
            txt = sg.strip('*').strip()
            if not re.search(r'\w', txt): continue
            y, _ = k.create(txt, voice=style, speed=float(sp * (.9 if emph else 1)), lang=lang)
            y = trim(y)
            if emph:
                y = shift(y, sr, st + 1.6 * a) * 10 ** (3 * a / 20)
                if chunk: chunk.append(np.zeros(int(.06 * sr), np.float32))
            else:
                y = shift(y, sr, st)
            chunk.append(np.asarray(y, np.float32))
            if emph: chunk.append(np.zeros(int(.04 * sr), np.float32))
        if not chunk: continue
        out.append(np.concatenate(chunk))
        if not last:
            end = p[-1]
            gap = (.34 if end in '.?!:;' else .62 if end == '…' else .26 if end == '—' else .16) + .05 * rng.random()
            gap *= lerp(1, T['pause'])
            out.append(np.zeros(int(gap * .45 * sr), np.float32))
            if end in '.?!:…' and rng.random() < lerp(.5, T['breath']): out.append(breath(rng, sr))
            out.append(np.zeros(int(gap * .55 * sr), np.float32))
    y = fx(np.concatenate(out).astype(np.float64), sr)
    y = y / (np.max(np.abs(y)) + 1e-9) * .7 * 10 ** (lerp(0, T['db']) / 20)
    return y.astype(np.float32), sr

def cmd_moods(job):
    return {'moods': {**{k: v['label'] for k, v in MOODS.items()}, **REAL_MOODS}}

def cmd_voices(job):
    return {'voices': [{'id': k, 'label': v['label'], 'lang': v['lang']} for k, v in VOICES.items()]}

def cmd_tts(job):
    k = kokoro(job['modelDir'])
    v = VOICES[job['voice']]
    base = {}
    for n, w in v['mix']: base[n] = base.get(n, 0) + w
    fr = v['lang'].startswith('fr')
    os.makedirs(job['outDir'], exist_ok=True)
    amount = float(job.get('expressiveness', .8))
    res = []
    for i, line in enumerate(job['lines']):
        tone = line.get('tone') or 'neutral'
        mix = dict(base)
        for n, w in TONES.get(tone, TONES['neutral'])['blend'].items():      # timbre nudge (smaller for French, to keep the accent)
            mix[n] = mix.get(n, 0) + w * amount * (.35 if fr else 1)
        tot = sum(mix.values()); style = sum(w / tot * k.get_voice_style(n) for n, w in mix.items())
        s, sr = speak(k, line['text'], style, v['lang'], job.get('speed', 1.03), seed=i + 1, tone=tone, amount=amount)
        f = os.path.join(job['outDir'], f"{line['id']}.wav"); sf.write(f, s, sr)
        env, zcr = envelope(s, sr)
        res.append({'id': line['id'], 'file': f, 'dur': round(len(s) / sr, 3), 'env': env, 'zcr': zcr, 'tone': tone})
    return {'lines': res}

def cmd_analyze(job):
    raw = subprocess.run(['ffmpeg', '-loglevel', 'error', '-i', job['input'], '-f', 'f32le', '-ac', '1', '-ar', '24000', '-'], capture_output=True, check=True).stdout
    s = np.frombuffer(raw, np.float32).astype(np.float64)
    s = sosfilt(butter(2, 80, 'high', fs=24000, output='sos'), s)
    if len(s) == 0 or np.max(np.abs(s)) < 1e-3: raise SystemExit('The recording is silent or empty: check the file and try again.')
    nz = np.where(np.abs(s) > .02 * np.max(np.abs(s)))[0]
    s = s[max(0, nz[0] - 1200): nz[-1] + 2400] if len(nz) else s
    s = (s / (np.max(np.abs(s)) + 1e-9) * .9).astype(np.float32)
    sf.write(job['out'], s, 24000)
    env, zcr = envelope(s, 24000)
    return {'file': job['out'], 'dur': round(len(s) / 24000, 3), 'env': env, 'zcr': zcr}

# ------------------------------------------------------------------ music (sampled instruments, CC BY 3.0 FluidR3_GM)
SR = 48000
SAMPLE_URL = 'https://raw.githubusercontent.com/gleitz/midi-js-soundfonts/gh-pages/FluidR3_GM/{inst}-mp3/{note}.mp3'
NAMES = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B']
_cache = {}
def sample(sdir, inst, m):
    key = (inst, m)
    if key in _cache: return _cache[key]
    f = os.path.join(sdir, inst, f'{m}.mp3')
    if not os.path.exists(f):
        os.makedirs(os.path.dirname(f), exist_ok=True)
        urllib.request.urlretrieve(SAMPLE_URL.format(inst=inst, note=f'{NAMES[m % 12]}{m // 12 - 1}'), f)
    raw = subprocess.run(['ffmpeg', '-loglevel', 'error', '-i', f, '-f', 'f32le', '-ac', '1', '-ar', str(SR), '-'], capture_output=True).stdout
    x = np.frombuffer(raw, np.float32).astype(np.float64); i = int(np.argmax(np.abs(x) > .002)); _cache[key] = x[max(0, i - 48):]
    return _cache[key]

REAL_MOODS = {'pop': 'Bright pop on real instruments (acoustic guitar, piano, bass, real drums)', 'acoustic': 'Warm acoustic (fingerpicked guitar, piano, shaker)'}
MOODS = {
  'lofi':  {'bpm': 80, 'keys': 'electric_piano_1', 'chords': [(41, [52, 57, 60, 64, 67]), (40, [50, 55, 59, 62, 67]), (38, [48, 53, 57, 60, 64]), (43, [47, 52, 55, 59, 64])], 'drums': True,  'label': 'Soft lo-fi (electric piano, round bass, light drums)'},
  'piano': {'bpm': 72, 'keys': 'acoustic_grand_piano', 'chords': [(36, [52, 55, 60, 64]), (43, [50, 55, 59, 62]), (45, [52, 57, 60, 64]), (41, [53, 57, 60, 65])], 'drums': False, 'label': 'Calm piano, no drums'},
  'upbeat': {'bpm': 100, 'keys': 'acoustic_guitar_nylon', 'chords': [(36, [48, 52, 55, 60, 64]), (43, [43, 47, 50, 55, 59]), (45, [45, 52, 57, 60, 64]), (41, [41, 48, 53, 57, 60])], 'drums': True, 'label': 'Bright and light (nylon guitar, claps)'},
  'halloween': {'bpm': 76, 'keys': 'celesta', 'chords': [(45, [57, 60, 64, 69]), (41, [57, 60, 65, 69]), (38, [57, 62, 65, 69]), (40, [56, 59, 64, 68])], 'drums': False, 'label': 'Playful Halloween music box (celesta, A minor, no drums)'},
}

def cmd_music(job):
    mood = job['mood']; D = float(job['duration']); sdir = job['samplesDir']
    out = job['out']
    if mood == 'none':
        sf.write(out, np.zeros((int(D * SR), 2), np.float32), SR); return {'file': out, 'mood': 'none'}
    if mood in REAL_MOODS:
        import realmusic
        return finish(realmusic.build(mood, D, sdir), job, D, out, mood)
    M = MOODS[mood]; BEAT = 60 / M['bpm']; BAR = 4 * BEAT; L = int((D + 3) * SR)
    rng = np.random.default_rng(7)
    bus = {k: np.zeros((2, L)) for k in ('keys', 'bass', 'drums')}
    def put(b, y, t0, pan=0., g=1.):
        i = int(round(t0 * SR)); n = min(len(y), L - i)
        if n <= 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 note(b, inst, m, t0, dur, vel, pan=0., rel=.35):
        x = sample(sdir, 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); put(b, y, t0, pan, vel)
    tt = lambda d: np.arange(int(d * SR)) / SR
    lp = lambda x, f: sosfilt(butter(2, f, 'low', fs=SR, output='sos'), x)
    bp = lambda x, a, b: sosfilt(butter(2, [a, b], 'band', fs=SR, output='sos'), x)
    def kick(v): t = tt(.4); f = 45 + 55 * np.exp(-t * 25); return lp(np.sin(2 * np.pi * np.cumsum(f) / SR) * np.exp(-t * 8), 900) * v
    def snare(v): t = tt(.3); return (bp(rng.standard_normal(len(t)), 900, 4500) * np.exp(-t * 14) * .7 + np.sin(2 * np.pi * 180 * t) * np.exp(-t * 25) * .4) * v
    def hat(v): t = tt(.07); return bp(rng.standard_normal(len(t)), 5000, 9000) * np.exp(-t * 60) * v
    for bar in range(int(np.ceil(D / BAR)) + 1):
        T = bar * BAR; bass, voic = M['chords'][bar % 4]
        sw = lambda k: k * BEAT / 2 + (.05 if k % 2 else 0)
        for j, m in enumerate(voic): note('keys', M['keys'], m, T + .02 + j * .018, BAR * .95, .28, -.3 + j * .15, rel=.5)
        for j, m in enumerate(voic[1:4]): note('keys', M['keys'], m, T + 2.5 * BEAT + .05 + j * .015, BEAT * 1.1, .13, .2)
        if bar >= 1:
            note('bass', 'acoustic_bass', max(28, min(52, bass)), T, BEAT * 1.6, .7)
            if M['drums']:
                put('drums', kick(.75), T); put('drums', kick(.5), T + 2.5 * BEAT)
                put('drums', snare(.3), T + BEAT + .03, .1); put('drums', snare(.32), T + 3 * BEAT + .03, .1)
                for k in range(8): put('drums', hat(.09 if k % 2 else .06), T + sw(k), .3)
    keys = np.stack([lp(bus['keys'][c], 7000) for c in range(2)])
    mix = keys + bus['bass'] * .8 + np.stack([lp(bus['drums'][c], 7000) for c in range(2)]) * .7
    t_ = tt(1.6); ir = rng.standard_normal((2, len(t_))) * np.exp(-t_ * 3.5); ir[:, :int(.01 * SR)] = 0
    mix = mix + np.stack([fftconvolve(keys[c], ir[c])[:L] for c in range(2)]) * .012
    mix = mix[:, :int(D * SR)]
    mix = np.tanh(mix / (np.percentile(np.abs(mix), 99.9) + 1e-9) * 1.05)
    return finish(mix, job, D, out, mood)

def finish(mix, job, D, out, mood):
    duck = np.ones(mix.shape[1])                                   # -9 dB under the voice
    for v in job.get('voice', []):
        a, b = int((v['start'] - .1) * SR), int((v['start'] + v['dur'] + .15) * SR); duck[max(0, a):b] = .36
    lp1 = butter(1, 4, 'low', fs=SR, output='sos'); duck = sosfilt(lp1, duck); duck = sosfilt(lp1, duck[::-1])[::-1]
    n = mix.shape[1]; fi = np.clip(np.arange(n) / SR, 0, 1); fo = np.clip((D - np.arange(n) / SR) / 2.0, 0, 1)
    mix = mix * duck * fi * fo
    mix = mix / (np.max(np.abs(mix)) + 1e-9) * .5
    sf.write(out, mix.T.astype(np.float32), SR)
    return {'file': out, 'mood': mood}

# ------------------------------------------------------------------ sound effects (Kenney, CC0) on the animation cues
def cmd_sfx(job):
    D = float(job['duration']); n = int(D * SR); out = np.zeros((2, n + SR))
    sdir = os.path.join(HERE, 'sfx'); cache = {}
    rng = np.random.default_rng(3)
    def load(name):
        if name not in cache:
            x, sr = sf.read(os.path.join(sdir, name + '.wav')); x = x.mean(1) if x.ndim > 1 else x
            cache[name] = resample_poly(x, SR, sr) if sr != SR else x
        return cache[name]
    def put(y, t, g, pan=0.):
        i = int(t * SR); m = min(len(y), out.shape[1] - i)
        if m <= 0 or i < 0: return
        out[0, i:i + m] += y[:m] * g * np.cos((pan + 1) * np.pi / 4) * 1.414
        out[1, i:i + m] += y[:m] * g * np.sin((pan + 1) * np.pi / 4) * 1.414
    def whoosh(strength):
        d = .42; t = np.arange(int(d * SR)) / SR; x = rng.standard_normal(len(t))
        y = np.zeros_like(x); seg = len(t) // 12
        for k in range(12):                                   # band sweeping up then down, like air moving past
            c = 500 + 2600 * np.sin(np.pi * (k + .5) / 12) ** 1.5
            sos = butter(2, [c * .6, c * 1.4], 'band', fs=SR, output='sos'); a, b = k * seg, (k + 1) * seg if k < 11 else len(t)
            y[a:b] = sosfilt(sos, x[max(0, a - 400):b])[-(b - a):]
        env = np.sin(np.pi * np.clip(t / d, 0, 1)) ** 2.2
        return y * env * .5 * strength
    for e in job['events']:
        t = e['t']
        if e['type'] == 'whoosh': put(whoosh(e.get('strength', 1)), t, .55, rng.uniform(-.4, .4))
        elif e['type'] == 'pop':
            name = ['drop_002', 'drop_003'][e.get('n', 0) % 2]
            put(load(name), t, .32, (-.25, .25)[e.get('n', 0) % 2]); put(load('click_002'), t, .12)
        elif e['type'] == 'ding': put(load('glass_002'), t, .45)
        elif e['type'] == 'chime': put(load('confirmation_002'), t, .35)
    out = out[:, :n]
    sf.write(job['out'], out.T.astype(np.float32), SR)
    return {'file': job['out'], 'count': len(job['events'])}

def cmd_ambience(job):
    import ambience
    return ambience.build(job['scenes'], float(job['duration']), job['out'])

def cmd_mix(job):
    D = float(job['duration']); n = int(D * SR)
    if job.get('music') and os.path.exists(job['music']):
        mus, sr = sf.read(job['music'], always_2d=True); mus = mus[:n]
        if len(mus) < n: mus = np.vstack([mus, np.zeros((n - len(mus), 2))])
    else: mus = np.zeros((n, 2))
    vo = np.zeros(n)
    for v in job['voice']:
        s, sr = sf.read(v['file']); s = resample_poly(s, SR, sr) if sr != SR else s
        i = int(v['start'] * SR); m = min(len(s), n - i)
        if m > 0: vo[i:i + m] += s[:m]
    if np.max(np.abs(vo)) > 0: vo = vo / np.max(np.abs(vo)) * .85
    mix = mus * float(job.get('musicGain', .9)) + np.stack([vo, vo], 1)
    if job.get('ambience') and os.path.exists(job['ambience']):
        am, sr = sf.read(job['ambience'], always_2d=True); am = am[:n]
        duck = np.ones(len(am))                                   # a little lower under the voice
        for v in job['voice']:
            a = int(v['start'] * SR); duck[max(0, a - 4800):a + int(sf.info(v['file']).duration * SR) + 7200] = .6
        duck = sosfilt(butter(1, 3, 'low', fs=SR, output='sos'), duck)
        mix[:len(am)] += am * duck[:, None] * float(job.get('ambienceGain', 1.0))
    if job.get('sfx') and os.path.exists(job['sfx']):
        fx_, sr = sf.read(job['sfx'], always_2d=True); fx_ = fx_[:n]
        mix[:len(fx_)] += fx_ * float(job.get('sfxGain', .8))
    mix = mix / (np.max(np.abs(mix)) + 1e-9) * .89
    sf.write(job['out'], mix.astype(np.float32), SR)
    if job.get('mp3'): subprocess.run(['ffmpeg', '-loglevel', 'error', '-y', '-i', job['out'], '-b:a', '160k', job['mp3']], check=True)
    return {'file': job['out'], 'mp3': job.get('mp3')}

if __name__ == '__main__':
    cmd, job = sys.argv[1], (json.load(open(sys.argv[2])) if len(sys.argv) > 2 else {})
    print(json.dumps(globals()['cmd_' + cmd](job)))
