"""Scribe-Wrapper für ElevenLabs /v1/speech-to-text — liefert Wort-Timestamps als JSON."""

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))

import argparse, json  # noqa: E401
import requests  # noqa: E402
from find_api_key import get_elevenlabs_key  # noqa: E402

SCRIBE_URL = "https://api.elevenlabs.io/v1/speech-to-text"
DEFAULT_MODEL = "scribe_v1"

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="ElevenLabs Scribe — Audio zu Wort-Timestamps")
    parser.add_argument("audio", help="Pfad zur Eingabe-Audio-Datei")
    parser.add_argument("--output", default="output.json", help="Ausgabe-Pfad für JSON mit Wort-Timestamps")
    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)

    audio_path = Path(args.audio)
    if not audio_path.exists():
        print(f"Audio-Datei nicht gefunden: {audio_path}", file=sys.stderr)
        sys.exit(1)

    with audio_path.open("rb") as audio_file:
        response = requests.post(
            SCRIBE_URL,
            headers={"xi-api-key": api_key},
            files={"file": audio_file},
            data={"model_id": DEFAULT_MODEL},
            timeout=120,
        )
    response.raise_for_status()
    Path(args.output).write_text(json.dumps(response.json(), ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"Wort-Timestamps gespeichert: {args.output}")
