#!/usr/bin/env python3
"""Turn a reading script into an audio file with chapters, ready for `pod add`.

  pod-tts SCRIPT.json OUT.mp3 [--engine mistral|elevenlabs] [--voice ID] [--sample N]

SCRIPT.json: {"title": "...", "artist": "...", "sections": [{"title": "...", "text": "..."}]}
Paragraphs in "text" are separated by blank lines. One chapter per section.
--sample N: only synthesize the first N characters of the first section (voice A/B test).
Keys: ~/.config/pod/mistral-key, ~/.config/pod/elevenlabs-key (one line, only the key)
"""

import argparse
import base64
import json
import shutil
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
from pathlib import Path

CHUNK = 2500
PAUSE = 0.8
DEFAULT_VOICE = {"elevenlabs": None, "mistral": "voice_481"}


def die(msg):
    print(f"FEHLER: {msg}", file=sys.stderr)
    sys.exit(1)


def key(name):
    p = Path.home() / ".config" / "pod" / name
    if not p.exists():
        die(f"{p} fehlt")
    return p.read_text().strip()


def post(url, headers, body, timeout=300):
    req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST",
                                 headers={"Content-Type": "application/json", **headers})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.read(), r.headers.get("Content-Type", "")
    except urllib.error.HTTPError as e:
        die(f"{url} → HTTP {e.code}: {e.read()[:400].decode(errors='replace')}")


def tts_elevenlabs(text, voice, prev, nxt):
    body = {
        "text": text,
        "model_id": "eleven_multilingual_v2",
        "language_code": "de",
        "voice_settings": {"stability": 0.5, "similarity_boost": 0.8, "style": 0.1,
                           "use_speaker_boost": True, "speed": 1.0},
    }
    if prev:
        body["previous_text"] = prev[-1000:]
    if nxt:
        body["next_text"] = nxt[:1000]
    data, _ = post(f"https://api.elevenlabs.io/v1/text-to-speech/{voice}?output_format=mp3_44100_128",
                   {"xi-api-key": key("elevenlabs-key")}, body)
    return data


def tts_mistral(text, voice, prev, nxt):
    body = {"model": "voxtral-mini-tts-3-0", "input": text, "voice_id": voice, "response_format": "mp3"}
    data, _ = post("https://api.mistral.ai/v1/audio/speech",
                   {"Authorization": f"Bearer {key('mistral-key')}"}, body)
    return base64.b64decode(json.loads(data)["audio_data"])


ENGINES = {"elevenlabs": tts_elevenlabs, "mistral": tts_mistral}


def chunks(text):
    paras = [p.strip() for p in text.split("\n\n") if p.strip()]
    out, cur = [], ""
    for p in paras:
        if cur and len(cur) + len(p) + 2 > CHUNK:
            out.append(cur)
            cur = p
        else:
            cur = f"{cur}\n\n{p}" if cur else p
    if cur:
        out.append(cur)
    return out


def duration(path):
    return float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
                                 "-of", "csv=p=0", str(path)], capture_output=True, text=True).stdout)


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("script")
    p.add_argument("out")
    p.add_argument("--engine", choices=ENGINES, default="mistral")
    p.add_argument("--voice")
    p.add_argument("--sample", type=int)
    a = p.parse_args()

    script = json.loads(Path(a.script).read_text())
    sections = script["sections"]
    if a.sample:
        first = sections[0]["text"][: a.sample]
        first = first[: first.rfind(".") + 1] or first
        sections = [{"title": sections[0]["title"], "text": first}]
    voice = a.voice or DEFAULT_VOICE[a.engine]
    if not voice:
        die("Für ElevenLabs bitte --voice <Voice-ID> angeben (in der Voice Library von ElevenLabs)")
    tts = ENGINES[a.engine]

    pieces = [(si, c) for si, s in enumerate(sections) for c in chunks(s["text"])]
    chars = sum(len(c) for _, c in pieces)
    print(f"▶ {a.engine} · {len(sections)} Abschnitte · {len(pieces)} Teile · {chars} Zeichen", file=sys.stderr)

    with tempfile.TemporaryDirectory() as tmp:
        tmp = Path(tmp)
        wavs, chapters, t, last_section = [], [], 0.0, None
        silence = tmp / "silence.wav"
        subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono",
                        "-t", str(PAUSE), str(silence)], check=True)
        for i, (si, text) in enumerate(pieces):
            if si != last_section:
                if wavs:
                    wavs.append(silence)
                    t += PAUSE
                chapters.append({"start": f"{t:.3f}", "title": sections[si]["title"]})
                last_section = si
            prev = pieces[i - 1][1] if i else ""
            nxt = pieces[i + 1][1] if i + 1 < len(pieces) else ""
            raw = tmp / f"p{i:03d}.audio"
            raw.write_bytes(tts(text, voice, prev, nxt))
            wav = tmp / f"p{i:03d}.wav"
            subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(raw), "-ac", "1", "-ar", "44100",
                            str(wav)], check=True)
            wavs.append(wav)
            t += duration(wav)
            print(f"  {i + 1}/{len(pieces)} ✓", file=sys.stderr)

        lst = tmp / "list.txt"
        lst.write_text("".join(f"file '{w}'\n" for w in wavs))
        full = tmp / "full.wav"
        subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", str(lst),
                        "-c", "copy", str(full)], check=True)
        chap = tmp / "chapters.json"
        chap.write_text(json.dumps(chapters, ensure_ascii=False))
        cmd = [shutil.which("pod") or str(Path.home() / ".local" / "bin" / "pod"), "cut", str(full), a.out, "--chapters", str(chap),
               "--title", script["title"]]
        if script.get("artist"):
            cmd += ["--artist", script["artist"]]
        if subprocess.run(cmd).returncode:
            die("pod cut fehlgeschlagen")


if __name__ == "__main__":
    main()
