#!/usr/bin/env python3
"""precis-tts-run — render a voice-score to audio, one-shot, in the precis-tts
container.

Reads a ``segments.json`` (the voice-score the precis worker built with
``render_narration`` / ``markdown_segments``), synthesizes each segment (misaki-
routed for zh/ja), stitches into one track, and encodes to mp3 **once** at the
end. mp3 is the one format that plays everywhere (incl. Apple/iOS), so a shared
enclosure just works. The precis worker stages the input + reads the output over
a bind mount, so it never needs the ``[tts]`` extra itself.

  in : /work/in/segments.json
       {"segments": [{"text","voice","lang","kind","gap_after"}, ...],
        "speed": 1.0}
       ``gap_after`` (seconds, nullable) is a per-segment trailing-silence
       override — a content property of the segment, not a top-level pause
       knob; ``null``/absent falls back to the stitch's kind-based default.
  out: /work/out/out.mp3   (+ /work/out/result.json with {segments, duration_s})

Dependency-light: reuses ``precis.export.audio.synthesize_text`` (the shared
stitch loop) + ``precis.tts.kokoro.KokoroSynth``.
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path


def main() -> int:
    ap = argparse.ArgumentParser(description="render a voice-score to mp3")
    ap.add_argument("--in", dest="inp", default="/work/in/segments.json")
    ap.add_argument("--out", dest="out", default="/work/out/out.mp3")
    args = ap.parse_args()

    from precis.draft.narrate import NarrationSegment
    from precis.export.audio import synthesize_text
    from precis.tts.encode import encode_mp3
    from precis.tts.kokoro import KokoroSynth

    data = json.loads(Path(args.inp).read_text(encoding="utf-8"))
    segs = [
        NarrationSegment(
            text=s["text"],
            voice=s["voice"],
            lang=s["lang"],
            kind=s.get("kind", "para"),
            gap_after=s.get("gap_after"),
        )
        for s in data.get("segments", [])
        if s.get("text")
    ]
    if not segs:
        print("precis-tts-run: no segments to render", file=sys.stderr)
        return 2

    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    wav = out.with_suffix(".wav")
    synth = KokoroSynth(speed=float(data.get("speed", 1.0)))
    res = synthesize_text(segs, wav, synth=synth)
    encode_mp3(wav, out)  # the one shared WAV→mp3 encode (precis.tts.encode)
    wav.unlink(missing_ok=True)
    result = {"segments": res.segments, "duration_s": round(res.duration_s, 2)}
    (out.parent / "result.json").write_text(json.dumps(result), encoding="utf-8")
    print(json.dumps(result))
    return 0


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