#!/usr/bin/env python3
"""Turns a plain-text script into an MP3 with the open-source Kokoro voice. No API key, no cost.

Usage:  python speak.py script.txt episode.mp3 --voice af_heart
The first run downloads the voice model (about 340 MB) into ./models.
"""
from __future__ import annotations

import argparse
import json
import re
import sys
import time
import urllib.request
from pathlib import Path

MODEL_BASE = 'https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/'
MODEL_FILES = ('kokoro-v1.0.onnx', 'voices-v1.0.bin')
# The first letter of a Kokoro voice name gives its language.
LANGUAGES = {'a': 'en-us', 'b': 'en-gb', 'e': 'es-419', 'f': 'fr-fr', 'h': 'hi', 'i': 'it', 'p': 'pt-br'}
MAX_CHARS = 300


def ensure_models(folder: Path) -> list[Path]:
    folder.mkdir(parents=True, exist_ok=True)
    paths = []
    for name in MODEL_FILES:
        path = folder / name
        if not path.exists():
            print(f'Downloading {name}...', flush=True)
            part = path.with_name(name + '.part')
            urllib.request.urlretrieve(MODEL_BASE + name, part)
            part.rename(path)
        paths.append(path)
    return paths


def clean(text: str, pronunciations: dict[str, str]) -> str:
    """Removes anything a voice would read aloud by mistake, then applies the user's respellings."""
    text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
    text = re.sub(r'https?://\S+', '', text)
    text = re.sub(r'^\s*(#{1,6}|>|[-*•]\s)\s*', '', text, flags=re.M)
    text = re.sub(r'^\s*[-_*]{3,}\s*$', '', text, flags=re.M)
    text = re.sub(r'[*_`]', '', text)
    for written, spoken in pronunciations.items():
        text = re.sub(rf'(?<!\w){re.escape(written)}(?!\w)', lambda _: spoken, text)
    return text.strip()


def split_long(sentence: str) -> list[str]:
    if len(sentence) <= MAX_CHARS:
        return [sentence]
    return pack(re.split(r'(?<=[,;:])\s+', sentence), fallback=True)


def pack(pieces: list[str], fallback: bool = False) -> list[str]:
    chunks, current = [], ''
    for piece in pieces:
        if fallback and len(piece) > MAX_CHARS:
            words = piece.split()
        else:
            words = [piece]
        for word in words:
            if current and len(current) + len(word) + 1 > MAX_CHARS:
                chunks.append(current)
                current = word
            else:
                current = f'{current} {word}'.strip()
    return chunks + ([current] if current else [])


def paragraphs(text: str) -> list[list[str]]:
    result = []
    for block in re.split(r'\n\s*\n', text):
        sentences = re.split(r'(?<=[.!?…।])\s+', ' '.join(block.split()))
        parts = [p for s in sentences if s for p in split_long(s)]
        if parts:
            result.append(pack(parts))
    return result


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('script', type=Path)
    ap.add_argument('output', type=Path)
    ap.add_argument('--voice', default='af_heart')
    ap.add_argument('--speed', type=float, default=1.0)
    ap.add_argument('--pronunciations', type=Path)
    ap.add_argument('--models', type=Path, default=Path(__file__).resolve().parent / 'models')
    args = ap.parse_args()

    language = LANGUAGES.get(args.voice[:1])
    if not language:
        sys.exit(f'Voice "{args.voice}" is not supported. Names start with one of: {", ".join(LANGUAGES)}')
    words = {}
    if args.pronunciations and args.pronunciations.exists():
        words = json.loads(args.pronunciations.read_text(encoding='utf-8')).get('words', {})
    blocks = paragraphs(clean(args.script.read_text(encoding='utf-8'), words))
    if not blocks:
        sys.exit('The script is empty.')

    import lameenc
    import numpy as np
    from kokoro_onnx import Kokoro

    model, voices = ensure_models(args.models)
    kokoro = Kokoro(str(model), str(voices))
    started = time.time()
    encoder, mp3, samples_total, rate = None, bytearray(), 0, 24000
    total = sum(len(b) for b in blocks)
    done = 0
    for block in blocks:
        for i, chunk in enumerate(block):
            audio, rate = kokoro.create(chunk, voice=args.voice, speed=args.speed, lang=language)
            if encoder is None:
                encoder = lameenc.Encoder()
                encoder.set_bit_rate(64)
                encoder.set_in_sample_rate(rate)
                encoder.set_channels(1)
                encoder.set_quality(2)
            pause = 0.8 if i == len(block) - 1 else 0.2
            audio = np.concatenate([audio, np.zeros(int(rate * pause), dtype=audio.dtype)])
            samples_total += len(audio)
            mp3 += encoder.encode((np.clip(audio, -1, 1) * 32767).astype(np.int16).tobytes())
            done += 1
            print(f'{done}/{total}', end='\r', flush=True)
    mp3 += encoder.flush()
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_bytes(mp3)
    print(json.dumps({'output': str(args.output), 'audio_seconds': round(samples_total / rate, 1),
                      'render_seconds': round(time.time() - started, 1), 'bytes': len(mp3)}))
    return 0


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