# /// script
# requires-python = ">=3.10"
# dependencies = ["pedalboard==0.9.26", "mido==1.3.3"]
# ///
"""Render a Meelmaky WAV or MIDI through an installed VST3 on this computer."""
import argparse
import shutil
import tempfile
from pathlib import Path

import mido
from pedalboard import load_plugin
from pedalboard.io import AudioFile


def render(plugin_path, source, destination, name=None, editor=False, tail=0.0):
    import numpy as np

    if destination.suffix.lower() != ".wav":
        raise ValueError("Choisis un fichier de sortie .wav.")
    if destination.exists():
        raise ValueError("Ce fichier existe déjà. Choisis un autre nom.")
    plugin = load_plugin(str(plugin_path), plugin_name=name)
    if editor:
        plugin.show_editor()
    if source.suffix.lower() in (".mid", ".midi"):
        if not plugin.is_instrument:
            raise ValueError("Un MIDI nécessite un instrument VST3.")
        midi = mido.MidiFile(source)
        elapsed = 0.0
        events = []
        for event in midi:
            elapsed += event.time
            if not event.is_meta:
                events.append((bytes(event.bytes()), elapsed))
        rate = 44100
        audio = plugin(events, duration=elapsed + tail, sample_rate=rate, num_channels=2)
    else:
        if not plugin.is_effect:
            raise ValueError("Un WAV nécessite un effet VST3.")
        with AudioFile(str(source)) as f:
            rate = f.samplerate
            samples = f.read(f.frames)
        if tail:
            samples = np.pad(samples, ((0, 0), (0, round(tail * rate))))
        try:
            audio = plugin(samples, rate)
        except ValueError as exc:
            if samples.shape[0] != 1 or "does not support 1-channel" not in str(exc):
                raise
            samples = np.repeat(samples, 2, axis=0)
            audio = plugin(samples, rate, reset=True)
        if audio.shape[1] < samples.shape[1]:
            missing = samples.shape[1] - audio.shape[1]
            flush = plugin(np.zeros((samples.shape[0], missing), dtype=np.float32), rate, reset=False)
            audio = np.concatenate((audio, flush), axis=1)
        if audio.shape[1] != samples.shape[1]:
            raise ValueError("Le plug-in a rendu une durée inattendue.")
    with tempfile.TemporaryDirectory(dir=destination.parent) as scratch:
        staged = Path(scratch) / "render.wav"
        with AudioFile(str(staged), "w", rate, audio.shape[0], bit_depth=24) as output:
            output.write(audio)
        with staged.open("rb") as source_file:
            new_file = destination.open("xb")
            try:
                with new_file:
                    shutil.copyfileobj(source_file, new_file)
            except BaseException:
                destination.unlink(missing_ok=True)
                raise


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("plugin", type=Path, nargs="?")
    parser.add_argument("source", type=Path, nargs="?")
    parser.add_argument("destination", type=Path, nargs="?")
    parser.add_argument("--name", help="Nom du plug-in dans un bundle qui en contient plusieurs.")
    parser.add_argument("--editor", action="store_true", help="Ouvrir les réglages avant le rendu.")
    parser.add_argument("--tail", type=float, default=0, help="Secondes de réverbération supplémentaires (0 à 30).")
    args = parser.parse_args()
    if not 0 <= args.tail <= 30:
        parser.error("--tail doit être compris entre 0 et 30.")
    if not any((args.plugin, args.source, args.destination)):
        from tkinter import Tk, filedialog, messagebox
        root = Tk()
        root.withdraw()
        # VST3 bundles may appear as folders or single files depending on the OS.
        directory = messagebox.askyesnocancel("Meelmaky VST3", "Ton plug-in .vst3 est-il un dossier ?")
        if directory is None:
            return
        chooser = filedialog.askdirectory if directory else filedialog.askopenfilename
        plugin = chooser(title="Choisis ton plug-in VST3")
        if not plugin:
            return
        source = filedialog.askopenfilename(title="Piste WAV ou motif MIDI")
        if not source:
            return
        output = filedialog.asksaveasfilename(title="Nouveau WAV de sortie", defaultextension=".wav")
        if not output:
            return
        try:
            render(Path(plugin), Path(source), Path(output), args.name, args.editor, args.tail)
        except Exception as exc:
            messagebox.showerror("Meelmaky VST3", str(exc))
            return
        messagebox.showinfo("Meelmaky VST3", "Rendu terminé.")
    elif all((args.plugin, args.source, args.destination)):
        render(args.plugin, args.source, args.destination, args.name, args.editor, args.tail)
    else:
        parser.error("Fournis le plug-in, le fichier source et le nouveau WAV de sortie.")


if __name__ == "__main__":
    main()
