from __future__ import annotations

import subprocess
from pathlib import Path

_EDGE_TTS = Path.home() / "miniconda3/bin/edge-tts"

# Voix par langue détectée (code ISO 639-1 -> voix edge-tts)
_VOICE_BY_LANG = {
    "fr": "fr-FR-DeniseNeural",
    "en": "en-US-AriaNeural",
    "es": "es-ES-ElviraNeural",
    "de": "de-DE-KatjaNeural",
    "it": "it-IT-ElsaNeural",
    "pt": "pt-BR-FranciscaNeural",
    "nl": "nl-NL-ColetteNeural",
    "ja": "ja-JP-NanamiNeural",
    "zh-cn": "zh-CN-XiaoxiaoNeural",
    "ko": "ko-KR-SunHiNeural",
    "ru": "ru-RU-SvetlanaNeural",
    "ar": "ar-SA-ZariyahNeural",
}
_DEFAULT_VOICE = "fr-FR-DeniseNeural"


def detect_voice(text: str) -> str:
    try:
        from langdetect import detect

        lang = detect(text).lower()
    except Exception:
        return _DEFAULT_VOICE
    if lang in _VOICE_BY_LANG:
        return _VOICE_BY_LANG[lang]
    # langdetect renvoie parfois "zh-tw" etc. — réduire au préfixe
    return _VOICE_BY_LANG.get(lang.split("-")[0], _DEFAULT_VOICE)


def synthesize(text: str, wav_path: Path, voice: str | None = None) -> None:
    voice = voice or detect_voice(text)
    mp3_path = wav_path.with_suffix(".mp3")
    subprocess.run(
        [str(_EDGE_TTS), "--text", text, "--voice", voice, "--write-media", str(mp3_path)],
        check=True,
        timeout=60,
        capture_output=True,
    )
    subprocess.run(
        ["ffmpeg", "-y", "-i", str(mp3_path), "-ar", "16000", "-ac", "1", str(wav_path)],
        check=True,
        capture_output=True,
    )
    mp3_path.unlink(missing_ok=True)
