"""Beats vs heterodyning: audio clips + figures (TD envelope, spectrum/spectrogram, 1 kHz lowpass).

Usage: python gen.py [output_dir]      (default: the current directory)
"""
import sys
from pathlib import Path

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from scipy.io import wavfile
from scipy.signal import hilbert, butter, sosfiltfilt, spectrogram

OUT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")
OUT.mkdir(parents=True, exist_ok=True)
FS = 48_000
LP = butter(8, 1000, fs=FS, output="sos")  # the "IF filter"


def tone(f, t):  # f may be an array (sweep): integrate phase
    return np.sin(2 * np.pi * np.cumsum(np.broadcast_to(f, t.shape)) / FS)


def wav(name, x, peak):  # shared peak keeps a filtered clip at its true relative level
    n = int(0.01 * FS)
    w = np.ones_like(x); w[:n] = w[-n:][::-1] = np.linspace(0, 1, n)
    wavfile.write(OUT / f"{name}.wav", FS, (0.7 * x * w / peak * 32767).astype(np.int16))


def figure(name, cases, zoom_ms, lp=True, band=None):
    """cases: [(label, signal)]. lp: add 1 kHz lowpass row. band: (lo, hi) Hz -> fine FFT instead of spectrogram."""
    rows = 2 + lp
    fig, ax = plt.subplots(rows, len(cases), figsize=(6 * len(cases), 3 * rows), squeeze=False)
    for j, (label, x) in enumerate(cases):
        t = np.arange(x.size) / FS
        k = (t >= zoom_ms[0] / 1e3) & (t < zoom_ms[1] / 1e3)
        a = ax[0, j]
        a.plot(t[k] * 1e3, x[k], lw=0.6); a.plot(t[k] * 1e3, np.abs(hilbert(x))[k], "r", lw=1.2)
        a.set(title=f"{label}: waveform + envelope (red)", xlabel="ms")
        a = ax[1, j]
        if band:
            X = np.fft.rfft(x * np.hanning(x.size)); f = np.fft.rfftfreq(x.size, 1 / FS)
            a.plot(f, 20 * np.log10(np.abs(X) / np.abs(X).max() + 1e-9))
            a.set(xlim=band, ylim=(-80, 3), title="spectrum (full-length FFT)", xlabel="Hz", ylabel="dB")
        else:
            f, tt, S = spectrogram(x, FS, nperseg=8192, noverlap=6144)
            a.pcolormesh(tt, f, 10 * np.log10(S + 1e-12), vmin=-90, shading="auto")
            a.set(ylim=(0, 5000), title="spectrogram", xlabel="s", ylabel="Hz")
        stem, peak = f"{name}_{label.split()[0].lower()}", np.abs(x).max()
        wav(stem, x, peak)
        if lp:
            y = sosfiltfilt(LP, x)
            rms = np.sqrt(np.mean(y**2))
            print(f"{stem}: rms in {np.sqrt(np.mean(x**2)):.3f}, after 1 kHz lowpass {rms:.3f}")
            a = ax[2, j]; a.plot(t[k] * 1e3, y[k], lw=0.8)
            a.set(ylim=(-1.1, 1.1), title=f"after 1 kHz lowpass (rms {rms:.3f})", xlabel="ms")
            wav(f"{stem}_lowpass", y, peak)
    fig.tight_layout(); fig.savefig(OUT / f"{name}.png", dpi=110); plt.close(fig)


t = np.arange(4 * FS) / FS
# 1. Addition only: slow beat (3 Hz) and roughness/dissonance (30 Hz). Spectrum: just the two tones.
figure("01_beats", [("Slow beat 440+443 Hz", tone(440, t) + tone(443, t)),
                    ("Rough 440+470 Hz", tone(440, t) + tone(470, t))], (0, 1000), lp=False, band=(400, 510))
# 2. Same pair, add vs multiply: 2000 & 2300 Hz -> product lines at 300 and 4300 Hz.
a, b = tone(2000, t), tone(2300, t)
figure("02_add_vs_mult", [("Sum 2000+2300 Hz", a + b), ("Product 2000x2300 Hz", a * b)], (100, 120))
# 3. Sweep 2000 Hz fixed x 2000->2600 Hz: only the product has a difference line, rising from 0 Hz.
t = np.arange(6 * FS) / FS
a, b = tone(2000, t), tone(np.linspace(2000, 2600, t.size), t)
figure("03_sweep", [("Sum sweep", a + b), ("Product sweep", a * b)], (3000, 3030))
