"""« Partage », a song of the WinZik Band made for WinZik (music, words and voice made here, free of rights: CC0).
Its lyrics are not shipped with it: they are on the marketplace of WinZik (jumphp.net), found by themselves.
Run from apps/winzik: python3 -I tools/sounds/partage.py <work dir>  (needs numpy, espeak-ng, sox), then encode the mp3.
"""
import os
import subprocess
import sys
import wave
import numpy as np

R = 22050
BPM = 110
BEAT = 60 / BPM
BAR = 4 * BEAT
OUT = sys.argv[1]
LINES = [
    "J'ai mis mon skin sur le réseau",
    "Pour qu'il voyage un peu plus haut",
    "Des paroles qui tombent du ciel",
    "Ligne à ligne, synchronisées",
    "Partage, partage, c'est gratuit",
    "Un clic et c'est déjà parti",
    "De Windows quatre-vingt-dix-huit",
    "Jusqu'à ton navigateur, tout de suite",
    "Partage, partage, à l'infini",
    "Tout le monde en profite aussi",
    "WinZik, WinZik, le son est là",
    "Et la playlist ne s'arrête pas",
]
FIRST = 4 * BAR                    # the first line after 4 bars
STEP = 2 * BAR                     # a line every 2 bars
TIMES = [round(FIRST + i * STEP, 3) for i in range(len(LINES))]


def tone(hz, dur, vol=.2, duty=.5, decay=5.0):
    t = np.arange(int(R * dur)) / R
    return np.where((t * hz) % 1 < duty, 1, -1) * np.exp(-t * decay) * vol


def nhz(n):
    return 440 * 2 ** ((n - 69) / 12)


total = int(R * (FIRST + len(LINES) * STEP + 2 * BAR))
mix = np.zeros(total)


def put(sig, at):
    i = int(at * R)
    mix[i:i + len(sig)] += sig[:max(0, total - i)]


# chords: G D Em C (a bar each), bass + arpeggio + drums all along
prog = [[55, 59, 62], [50, 54, 57], [52, 55, 59], [48, 52, 55]]
bars = int(total / R / BAR)
for b in range(bars):
    ch = prog[b % 4]
    for k in range(4):
        put(tone(nhz(ch[0] - 12), BEAT * .9, .3, .5, 3), (b * 4 + k) * BEAT)
    for s in range(8):
        put(tone(nhz(ch[s % 3] + 12), BEAT / 2 * .8, .06, .125, 8), (b * 4 + s / 2) * BEAT)
    for k in range(4):
        t = np.arange(int(R * .2)) / R
        if k % 2 == 0:
            put(np.sin(2 * np.pi * np.cumsum(100 * np.exp(-t * 25) + 45) / R) * np.exp(-t * 12) * .45, (b * 4 + k) * BEAT)
        else:
            put(np.random.default_rng(b * 4 + k).uniform(-1, 1, len(t)) * np.exp(-t * 25) * .15, (b * 4 + k) * BEAT)
# a little lead during the intro and the end
lead = [67, 71, 74, 71, 69, 67, 66, 67]
for i, n in enumerate(lead * 2):
    put(tone(nhz(n + 12), BEAT * .9, .07, .25, 4), i * BEAT)

# the voice: each line said by espeak-ng on its time, a bit lower and with some echo
for i, (line, at) in enumerate(zip(LINES, TIMES)):
    raw = os.path.join(OUT, f'l{i}.wav')
    fx = os.path.join(OUT, f'v{i}.wav')
    subprocess.run(['espeak-ng', '-v', 'fr+m3', '-s', '150', '-p', '45', '-a', '170', '-w', raw, line], check=True)
    subprocess.run(['sox', raw, '-r', str(R), '-c', '1', fx, 'pitch', '-150', 'reverb', '20', 'gain', '-n', '-2'], check=True,
                   stderr=subprocess.DEVNULL)
    w = wave.open(fx)
    v = np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16).astype(float) / 32768
    put(v * .9, at)

mix = mix / np.max(np.abs(mix)) * .9
w = wave.open(os.path.join(OUT, 'partage.wav'), 'wb')
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(R)
w.writeframes((mix * 32767).astype(np.int16).tobytes())
w.close()
with open(os.path.join(OUT, 'partage.lyr'), 'wb') as f:
    f.write(('[LYR]\r\n' + ''.join(f'[ {t} ]\r\n{l}\r\n' for t, l in zip(TIMES, LINES))).encode('cp1252'))
print(len(mix) / R, 's')
