"""TTS-Wrapper für ElevenLabs /v1/text-to-speech — erzeugt eine MP3-Audio-Datei."""

import os, sys, argparse  # noqa: E401
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))

import requests  # noqa: E402
from find_api_key import get_elevenlabs_key  # noqa: E402

TTS_URL = "https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
DEFAULT_MODEL = "eleven_multilingual_v2"

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="ElevenLabs TTS — Text zu MP3")
    parser.add_argument("text", help="Eingabe-Text für TTS")
    parser.add_argument("--voice-id", default=os.environ.get("ELEVENLABS_VOICE_ID", ""),
                        help="Premade Voice-ID. Default: ELEVENLABS_VOICE_ID-Env-Var.")
    parser.add_argument("--output", default="output.mp3", help="Ausgabe-Pfad (MP3)")
    args = parser.parse_args()

    api_key, _source = get_elevenlabs_key()
    if not api_key:
        print("Kein ELEVENLABS_API_KEY gefunden. Abbruch.", file=sys.stderr)
        sys.exit(1)

    voice_id = args.voice_id
    if not voice_id:
        print("Keine Voice-ID. Bitte --voice-id oder ELEVENLABS_VOICE_ID setzen.", file=sys.stderr)
        sys.exit(1)

    response = requests.post(
        TTS_URL.format(voice_id=voice_id),
        headers={"xi-api-key": api_key, "Content-Type": "application/json"},
        json={"text": args.text, "model_id": DEFAULT_MODEL},
        timeout=60,
    )
    response.raise_for_status()
    Path(args.output).write_bytes(response.content)
    print(f"Audio gespeichert: {args.output}")
