"""A short phrase in a profile's voice, to hear before using it (Configurações → Voz).

    voice_sample.py <profile_id> <out.wav> [--provider fish|cartesia|voicestudio|elevenlabs] [--phrase "..."]

Without `--provider`, tries the profile's providers in its order (the same a
video would) and writes the first WAV that comes out. With `--provider`, only
that one speaks, no fallback: the sample is from that provider or does not
exist. Prints the provider that spoke. The studio keeps the result by
provider, voice_id and phrase, so the same voice is not charged twice.
"""

import sys
from pathlib import Path

import requests

sys.path.insert(0, str(Path(__file__).resolve().parent))
import voice  # noqa: E402

PHRASE = "Esta é a minha voz. É assim que eu vou narrar os seus vídeos."


def main():
    args = sys.argv[1:]
    only, phrase = None, PHRASE
    for flag in ("--provider", "--phrase"):
        if flag in args:
            i = args.index(flag)
            if i + 1 >= len(args):
                print(__doc__, file=sys.stderr)
                return 2
            value = args[i + 1]
            del args[i : i + 2]
            if flag == "--provider":
                only = value
            else:
                phrase = value
    if len(args) != 2:
        print(__doc__, file=sys.stderr)
        return 2
    profile_id, out = args[0], Path(args[1])
    if only is not None and only not in voice.CLASSES:
        print(f"provedor desconhecido: {only}", file=sys.stderr)
        return 2
    data = {"voice": {"voice_profile": profile_id}}
    profile, reason = voice.voice_profile(data)
    if reason or profile is None:
        print(reason or f"a voz “{profile_id}” não existe", file=sys.stderr)
        return 1

    reasons = []
    chain = [voice.CLASSES[only](requests, data)] if only else voice.chain(requests, data)
    for provider in chain:
        not_ready = provider.ready()
        if not_ready:
            reasons.append(f"{voice.NAMES[provider.id]}: {not_ready}")
            continue
        try:
            audio = provider.generate({"id": "sample", "text": phrase})
        except voice.Failed as exc:
            reasons.append(str(exc))
            continue
        out.parent.mkdir(parents=True, exist_ok=True)
        tmp = out.with_suffix(".tmp")
        tmp.write_bytes(audio)
        tmp.replace(out)
        print(voice.NAMES[provider.id])
        return 0

    print("nenhum provedor falou: " + " · ".join(reasons), file=sys.stderr)
    return 1


if __name__ == "__main__":
    sys.exit(main())
