#!/usr/bin/env python3
"""
qwen3_tts.py — the MLX side of the `qwen3-mlx` TTS provider for `beehaven speak`.

WHY THIS EXISTS. Every other voice path `speak` can take is a network call
(cloud Kokoro, ElevenLabs) or a canned system voice (macOS `say`). None of them
can speak in *your* voice, and the cloud ones need a relay + a live token. This
script is the on-device path: Alibaba's Qwen3-TTS running under Apple's MLX,
which does 3-second voice cloning locally on Apple Silicon. No relay, no API
key, no audio leaves the machine.

CONTRACT WITH THE NODE SIDE (`src/tts-qwen3.ts`).
  - One JSON request object on **stdin**, one JSON response object on **stdout**.
  - stdout carries NOTHING ELSE. mlx-audio prints progress, tokens/sec, and
    "✅ Audio successfully generated" to stdout unconditionally, so every call
    into it is wrapped in `redirect_stdout(sys.stderr)`. The Node side parses
    stdout strictly, so a single stray print would corrupt the response.
  - Failures come back as `{"ok": false, "error": "..."}` with exit code 1 —
    the caller gets a message, never a Python traceback in the user's terminal.

COMMANDS
  probe       {}                          -> versions + whether Metal is usable
  transcribe  {audio}                     -> {text}         (whisper, clone-time only)
  speak       {text, out, ...}            -> {path, ...}    (synthesis)

WHY TRANSCRIBE IS A SEPARATE COMMAND. Qwen3-TTS clones via in-context learning:
it needs the reference audio AND a transcript of it. mlx-audio will happily
auto-transcribe at synthesis time, but that loads whisper-large-v3-turbo
(~1.6 GB) on *every* utterance. We transcribe ONCE when the voice is cloned,
persist the transcript in the voice profile, and pass `ref_text` on every
subsequent `speak` — so whisper never loads again and the profile stays a
self-contained, portable description of the voice.
"""

from __future__ import annotations

import json
import sys
import time
import wave
from contextlib import redirect_stdout
from pathlib import Path

# Model families. Voice CLONING requires a `-Base` checkpoint: CustomVoice is
# fixed predefined speakers and VoiceDesign builds a voice from a text
# description — neither accepts a reference recording.
DEFAULT_MODEL = "mlx-community/Qwen3-TTS-12Hz-0.6B-Base-4bit"
DEFAULT_STT_MODEL = "mlx-community/whisper-large-v3-turbo-asr-fp16"


def _fail(msg: str) -> None:
    """Emit the error envelope on stdout and leave with a non-zero status."""
    json.dump({"ok": False, "error": str(msg)}, sys.stdout)
    sys.stdout.write("\n")
    sys.stdout.flush()
    sys.exit(1)


def _ok(payload: dict) -> None:
    json.dump({"ok": True, **payload}, sys.stdout)
    sys.stdout.write("\n")
    sys.stdout.flush()


def cmd_probe(_req: dict) -> dict:
    import importlib.metadata as md

    import mlx.core as mx

    def _ver(pkg: str) -> str:
        try:
            return md.version(pkg)
        except Exception:
            return "?"

    # Touching the default device is the cheapest proof Metal actually
    # initializes — an x86 Python under Rosetta imports mlx fine and then dies
    # at the first kernel launch.
    device = str(mx.default_device())
    return {
        "python": sys.version.split()[0],
        "mlxAudio": _ver("mlx-audio"),
        "mlx": _ver("mlx"),
        "device": device,
        "defaultModel": DEFAULT_MODEL,
        "sttModel": DEFAULT_STT_MODEL,
    }


def cmd_transcribe(req: dict) -> dict:
    audio = req.get("audio")
    if not audio:
        raise ValueError("transcribe requires `audio`")
    audio_path = Path(audio).expanduser()
    if not audio_path.exists():
        raise FileNotFoundError(f"reference audio not found: {audio_path}")

    model_id = req.get("sttModel") or DEFAULT_STT_MODEL
    started = time.time()
    with redirect_stdout(sys.stderr):
        from mlx_audio.stt import load as load_stt

        stt = load_stt(model_id)
        # whisper takes the path directly and handles decode + resample, so we
        # don't have to guess the TTS model's sample rate here.
        result = stt.generate(str(audio_path), language=req.get("language"))
    text = (getattr(result, "text", "") or "").strip()
    if not text:
        raise RuntimeError(
            "transcription came back empty — is the reference audio silent or music-only?"
        )
    return {"text": text, "model": model_id, "elapsedSec": round(time.time() - started, 2)}


def cmd_speak(req: dict) -> dict:
    text = (req.get("text") or "").strip()
    if not text:
        raise ValueError("speak requires `text`")
    out = req.get("out")
    if not out:
        raise ValueError("speak requires `out` (destination .wav path)")

    out_path = Path(out).expanduser()
    out_path.parent.mkdir(parents=True, exist_ok=True)

    ref_audio = req.get("refAudio")
    ref_text = req.get("refText")
    if ref_audio:
        ref_audio = str(Path(ref_audio).expanduser())
        if not Path(ref_audio).exists():
            raise FileNotFoundError(f"reference audio not found: {ref_audio}")

    kwargs = {
        "text": text,
        "model": req.get("model") or DEFAULT_MODEL,
        # `join_audio` makes mlx-audio write exactly ONE file at
        # "<file_prefix>.<audio_format>" instead of one file per sentence
        # segment — that predictable name is how we find the result.
        "join_audio": True,
        "output_path": str(out_path.parent),
        "file_prefix": out_path.stem,
        "audio_format": out_path.suffix.lstrip(".") or "wav",
        "verbose": False,
        "play": False,
        "temperature": float(req.get("temperature", 0.7)),
        "speed": float(req.get("speed", 1.0)),
        "lang_code": req.get("langCode") or "en",
    }
    if ref_audio:
        kwargs["ref_audio"] = ref_audio
        # A Base checkpoint in ICL mode takes its identity entirely from the
        # reference, so blank the speaker — otherwise mlx-audio's `af_heart`
        # default (a Kokoro speaker name) rides along and muddies the logs.
        kwargs["voice"] = None
        # Passing ref_text keeps mlx-audio from loading whisper. When a caller
        # skips it (bare `--ref-audio` with no cached profile) mlx-audio falls
        # back to transcribing, which is slow but correct.
        if ref_text:
            kwargs["ref_text"] = ref_text
        else:
            kwargs["stt_model"] = req.get("sttModel") or DEFAULT_STT_MODEL
    elif req.get("voice"):
        # No reference recording: a predefined speaker (CustomVoice checkpoints).
        kwargs["voice"] = req["voice"]
    if req.get("instruct"):
        kwargs["instruct"] = req["instruct"]
    if req.get("maxTokens"):
        kwargs["max_tokens"] = int(req["maxTokens"])

    started = time.time()
    with redirect_stdout(sys.stderr):
        from mlx_audio.tts.generate import generate_audio

        generate_audio(**kwargs)

    if not out_path.exists():
        raise RuntimeError(
            f"synthesis reported success but produced no file at {out_path}"
        )

    duration = None
    try:
        with wave.open(str(out_path), "rb") as wf:
            duration = round(wf.getnframes() / float(wf.getframerate()), 2)
    except Exception:
        # Non-wav container (flac/mp3) — duration is a nicety, not a contract.
        pass

    elapsed = round(time.time() - started, 2)
    return {
        "path": str(out_path),
        "bytes": out_path.stat().st_size,
        "durationSec": duration,
        "elapsedSec": elapsed,
        # <1.0 means we generated faster than real time — the number that
        # decides whether this provider is usable interactively.
        "realTimeFactor": round(elapsed / duration, 2) if duration else None,
        "model": kwargs["model"],
        "cloned": bool(ref_audio),
    }


COMMANDS = {"probe": cmd_probe, "transcribe": cmd_transcribe, "speak": cmd_speak}


def main() -> None:
    command = sys.argv[1] if len(sys.argv) > 1 else ""
    handler = COMMANDS.get(command)
    if handler is None:
        _fail(f"unknown command {command!r} — expected one of {', '.join(COMMANDS)}")
        return

    raw = sys.stdin.read().strip()
    try:
        req = json.loads(raw) if raw else {}
    except json.JSONDecodeError as exc:
        _fail(f"invalid JSON request: {exc}")
        return

    try:
        _ok(handler(req))
    except Exception as exc:  # noqa: BLE001 — the envelope IS the error channel
        import traceback

        traceback.print_exc(file=sys.stderr)
        _fail(f"{type(exc).__name__}: {exc}")


if __name__ == "__main__":
    main()
