from __future__ import annotations

import html
import os
from typing import Iterable, Optional

from app.sales_brain.chunker import split_sentences


def build_ssml(
    text: str,
    voice: Optional[str] = None,
    rate: str = "0%",
    pitch: str = "0st",
    pause_ms: int = 250,
    locale: str = "en-US",
) -> str:
    voice_name = voice or os.getenv("SPEECH_VOICE", "en-US-Andrew:DragonHDLatestNeural")
    sentences = split_sentences(text)
    body_parts: list[str] = []
    for idx, sentence in enumerate(sentences):
        body_parts.append(html.escape(sentence, quote=True))
        if pause_ms > 0 and idx < len(sentences) - 1:
            body_parts.append(f'<break time="{pause_ms}ms"/>')
    body = " ".join(body_parts).strip()
    if not body:
        body = html.escape(text, quote=True)
    inner = f'<prosody rate="{rate}" pitch="{pitch}">{body}</prosody>'
    return (
        f'<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" '
        f'xml:lang="{locale}"><voice name="{voice_name}">{inner}</voice></speak>'
    )
