"""tkttsのEdge TTSバックエンド。

`pip install edge-tts` が必要です。Edge TTSの音声はMicrosoftのオンラインサービスから取得され、APIキーは不要です。

詳細説明:
このモジュールは、`tktts` ライブラリがMicrosoft Edge TTSサービスを利用してテキストを音声に変換するためのインターフェースを提供します。
非同期処理を同期的な`tktts`の枠組みに統合し、利用可能な音声の取得、音声ファイルへの保存、
そして対話形式のスクリプトの合成をサポートします。

:doc:`tktts_edge_usage`
"""

import asyncio
import os

import edge_tts

from tktts_base import apply_replacements, split_dialogue


TTS_ENGINE_NAME = "edge"
DEFAULT_EDGE_VOICE = "Nanami"
_voices_cache = None


def _run(coro):
    """Edge TTSのコルーチンを同期的なtkttsインターフェースから実行します。

    詳細説明:
    `asyncio.run` を使用して非同期処理を実行します。
    `RuntimeError` が発生した場合、特にイベントループが既に実行中のケースで、
    より分かりやすいエラーメッセージを提供し、ワーカーツレッドからの呼び出しを促します。

    :param coro: 実行するコルーチンオブジェクト。
    :type coro: `coroutine`
    :returns: コルーチンの実行結果。
    :rtype: `Any`
    :raises RuntimeError: アクティブなasyncioイベントループ内で実行された場合。
    """
    try:
        return asyncio.run(coro)
    except RuntimeError as exc:
        # This should not occur from speak.py, but makes the error actionable
        # when this backend is used from a notebook or GUI event loop.
        if "asyncio.run() cannot be called" in str(exc):
            raise RuntimeError(
                "Edge TTS cannot run inside an active asyncio event loop. "
                "Call this backend from a worker thread."
            ) from exc
        raise


async def _fetch_voices():
    """Edge TTSで利用可能な音声情報を非同期で取得し、キャッシュします。

    詳細説明:
    一度取得した音声情報は `_voices_cache` に格納され、次回の呼び出しからはキャッシュされたデータが使用されます。
    キャッシュが空の場合のみ、`edge_tts.list_voices()` を呼び出して最新の音声情報を取得します。

    :returns: 利用可能な音声情報のリスト。各要素はEdge TTSのAPIから返される辞書形式です。
    :rtype: `list[dict]`
    """
    global _voices_cache
    if _voices_cache is None:
        _voices_cache = await edge_tts.list_voices()
    return _voices_cache


def _voice_info(voice):
    """Edge TTSの生音声情報から、tkttsが使用する共通フォーマットの音声情報ディクショナリを作成します。

    :param voice: Edge TTSから取得した単一の音声情報ディクショナリ。
    :type voice: `dict`
    :returns: tktts形式の音声情報ディクショナリ。キーは 'name', 'locale', 'gender'。
    :rtype: `dict`
    """
    return {
        "name": voice["ShortName"],
        "locale": voice.get("Locale", ""),
        "gender": voice.get("Gender", ""),
    }


def get_available_voices_info():
    """利用可能なEdge TTS音声を、tkttsの共通音声情報フォーマットで返します。

    詳細説明:
    内部で非同期関数 `_fetch_voices` を呼び出してEdge TTSの音声リストを取得し、
    `_voice_info` を使って `tktts` の共通フォーマットに変換します。
    結果はShortNameでソートされて返されます。

    :returns: 利用可能な音声情報ディクショナリのリスト。各要素は `_voice_info` の戻り値と同じ形式です。
    :rtype: `list[dict]`
    """
    voices = _run(_fetch_voices())
    return [_voice_info(voice) for voice in sorted(voices, key=lambda v: v["ShortName"])]


def get_available_voices():
    """利用可能なEdge TTS音声の名前のリストを返します。

    詳細説明:
    `get_available_voices_info()` を呼び出し、その結果から音声の名前（`ShortName`）のみを抽出してリストとして返します。

    :returns: 利用可能な音声の名前（ShortName）のリスト。
    :rtype: `list[str]`
    """
    return [voice["name"] for voice in get_available_voices_info()]


def list_available_voices():
    """利用可能なEdge TTS音声の一覧をコンソールに出力します。

    詳細説明:
    音声名、ロケール、性別を整形して標準出力に表示します。
    音声の取得に失敗した場合はエラーメッセージを出力し、Falseを返します。

    :returns: 音声一覧の表示に成功した場合はTrue、失敗した場合はFalse。
    :rtype: `bool`
    """
    try:
        voices = get_available_voices_info()
    except Exception as exc:
        print(f"❌ Edge TTS の音声一覧を取得できませんでした: {exc}")
        return False

    print(f"=== 利用可能な {TTS_ENGINE_NAME} voices ===")
    for voice in voices:
        print(f"  {voice['name']:<40} {voice['locale']:<10} {voice['gender']}")
    print(f"\n{len(voices)} voice(s).")
    return True


async def _resolve_voice_async(keyword):
    """キーワードに基づいて、利用可能なEdge TTS音声の中から最適なものを非同期で解決します。

    詳細説明:
    以下の優先順位でキーワードに合致する音声を検索します。
    1. 短縮名 (e.g., `ja-JP-NanamiNeural`) と完全に一致
    2. 短縮名 (e.g., `ja-JP-NanamiNeural`) にキーワードが部分一致
    3. キーワードに "nanami" が含まれる音声
    4. ロケールが "ja" で始まり、性別が "Female" の音声
    上記のいずれにも一致しない場合、利用可能な音声リストの最初の音声が選択されます。

    :param keyword: 解決したい音声名またはキーワード。`None` の場合は `DEFAULT_EDGE_VOICE` が使用されます。
    :type keyword: `str` or `None`
    :returns: 解決されたEdge TTSのShortName。
    :rtype: `str`
    """
    voices = await _fetch_voices()
    keyword = str(keyword or DEFAULT_EDGE_VOICE).strip()

    # ShortName (e.g. ja-JP-NanamiNeural) is accepted as-is, while a short
    # name such as Nanami remains convenient for the existing voice maps.
    for voice in voices:
        if keyword.lower() == voice["ShortName"].lower():
            return voice["ShortName"]
    for voice in voices:
        if keyword.lower() in voice["ShortName"].lower():
            return voice["ShortName"]
    for voice in voices:
        if "nanami" in voice["ShortName"].lower():
            return voice["ShortName"]
    for voice in voices:
        if voice.get("Locale", "").lower().startswith("ja") and voice.get("Gender") == "Female":
            return voice["ShortName"]
    return voices[0]["ShortName"]


def _normalize_prosody(value, default="+0%"):
    """プロソディ（速さ、音量、ピッチ）の値をEdge TTSが認識する形式に正規化します。

    詳細説明:
    値が `None` または空の場合、デフォルト値を適用します。
    値が `%` や `Hz` で終わらない数値の場合、`%` を付加します。

    :param value: 正規化するプロソディの値（例: "0", "10", "+5%", "-2Hz"）。
    :type value: `str` or `int` or `float` or `None`
    :param default: 値がNoneまたは空の場合に適用するデフォルト値（例: "+0%"）。
    :type default: `str`
    :returns: 正規化されたプロソディ値の文字列（例: "+0%", "+5Hz"）。
    :rtype: `str`
    """
    value = str(value if value is not None else default).strip()
    if not value:
        return default
    if value.endswith("%") or value.endswith("Hz"):
        return value
    return f"{value}%"


def _select_voice(target_voices, speaker):
    """指定されたスピーカーに基づいてEdge TTSの音声を選択します。

    詳細説明:
    `target_voices` が文字列の場合、それを直接音声として使用します。
    `target_voices` が辞書の場合、スピーカー名に対応する音声名を検索します。
    スピーカー名が `Neural` で終わる場合、Edge TTSのフルIDとみなし、そのまま使用します。
    それ以外の場合、デフォルトの `DEFAULT_EDGE_VOICE` を使用します。

    :param target_voices: スピーカーと音声のマップ (dict) または単一の音声名 (str)。
    :type target_voices: `dict` or `str`
    :param speaker: 選択するスピーカー名。
    :type speaker: `str` or `None`
    :returns: 選択されたEdge TTSの音声ID (ShortName)。
    :rtype: `str`
    """
    if isinstance(target_voices, str):
        return target_voices

    mapped_voice = target_voices.get(speaker)
    if mapped_voice:
        return mapped_voice

    speaker_name = str(speaker or "").strip()
    if speaker_name.lower().endswith("neural"):
        return speaker_name
    return DEFAULT_EDGE_VOICE


async def _save_async(outfile, text, voice, rate, volume, pitch):
    """指定されたテキストをEdge TTSで音声ファイルとして非同期で保存します。

    詳細説明:
    `_resolve_voice_async` を使用して音声名を解決し、
    `edge_tts.Communicate` インスタンスを作成して音声ファイルを指定されたパスに保存します。

    :param outfile: 音声ファイルの出力パス。
    :type outfile: `str`
    :param text: 合成するテキスト。
    :type text: `str`
    :param voice: 使用する音声名またはキーワード。`_resolve_voice_async` で解決されます。
    :type voice: `str`
    :param rate: 音声の速さ（例: "+0%", "+10%"）。`_normalize_prosody` で正規化された値。
    :type rate: `str`
    :param volume: 音量（例: "+0%", "-5%"）。`_normalize_prosody` で正規化された値。
    :type volume: `str`
    :param pitch: ピッチ（例: "+0Hz", "-2Hz"）。`_normalize_prosody` で正規化された値。
    :type pitch: `str`
    :returns: 実際に使用されたEdge TTSの音声ID (ShortName)。
    :rtype: `str`
    """
    resolved_voice = await _resolve_voice_async(voice)
    communicate = edge_tts.Communicate(
        text=text,
        voice=resolved_voice,
        rate=rate,
        volume=volume,
        pitch=pitch,
    )
    await communicate.save(outfile)
    return resolved_voice


def speak(outfile, text, voice, rate="+0%", volume="+0%", pitch="+0Hz"):
    """指定されたテキストをEdge TTSで音声ファイルとして同期的に生成します。

    詳細説明:
    入力テキストが空でない場合、内部で非同期関数 `_save_async` を呼び出し、
    `_run` を使って同期的に実行します。音声生成に成功した場合はファイルパスを返し、
    失敗した場合はエラーメッセージを出力し `None` を返します。

    :param outfile: 音声ファイルの出力パス。
    :type outfile: `str`
    :param text: 合成するテキスト。
    :type text: `str`
    :param voice: 使用する音声名またはキーワード。
    :type voice: `str`
    :param rate: (オプション) 音声の速さ（例: "+0%", "+10%"）。デフォルトは"+0%"。
    :type rate: `str`
    :param volume: (オプション) 音量（例: "+0%", "-5%"）。デフォルトは"+0%"。
    :type volume: `str`
    :param pitch: (オプション) ピッチ（例: "+0Hz", "-2Hz"）。デフォルトは"+0Hz"。
    :type pitch: `str`
    :returns: 生成された音声ファイルのパス、または失敗した場合はNone。
    :rtype: `str` or `None`
    """
    if not str(text).strip():
        return None
    try:
        resolved_voice = _run(_save_async(outfile, text, voice, rate, volume, pitch))
        print(f"  Edge voice: {resolved_voice}")
        return outfile if os.path.isfile(outfile) else None
    except Exception as exc:
        print(f"❌ Edge TTS の音声生成に失敗しました: {exc}")
        return None


def speak_dialogue(dialogue, replacements, target_voices, speakers=None,
                   temp_dir=None, outfile=None, ext="mp3", cfg=None):
    """対話スクリプトの全セグメントをEdge TTSで合成し、一時的なMP3ファイルのパスのリストを返します。

    詳細説明:
    `tktts_base.split_dialogue` を使用して対話をスピーカーとテキストのセグメントに分割します。
    各セグメントに対して、テキスト置換を適用し、適切な音声を選択して `speak` 関数で音声ファイルを生成します。
    `cfg` オブジェクトからプロソディ設定（rate, volume, pitch）が取得され適用されます。
    一時ファイルは `temp_dir` に保存され、そのパスのリストが返されます。

    :param dialogue: 合成する対話セグメントのリスト。各要素は文字列またはタプルです。
    :type dialogue: `list`
    :param replacements: テキスト置換ルールを定義する辞書。`{元文字列: 置換文字列}` の形式。
    :type replacements: `dict`
    :param target_voices: スピーカー名と対応する音声名のマッピング、またはデフォルトの音声名。
    :type target_voices: `dict` or `str`
    :param speakers: (オプション) スピーカー設定の辞書。デフォルトは空の辞書。
    :type speakers: `dict` or `None`
    :param temp_dir: (オプション) 一時ファイルを保存するディレクトリ。指定しない場合はカレントディレクトリ。
    :type temp_dir: `str` or `None`
    :param outfile: (無視される) `tktts.py` でファイル結合が処理されるため、この引数は使用されません。
    :type outfile: `str` or `None`
    :param ext: (オプション) 出力する一時音声ファイルの拡張子（デフォルトは"mp3"）。
    :type ext: `str`
    :param cfg: (オプション) `tktts` の設定オブジェクト。プロソディ設定（`edge_rate`, `edge_volume`, `edge_pitch`）が含まれる場合がある。
    :type cfg: `object` or `None`
    :returns: (成功フラグ, 一時ファイルパスのリスト)。成功フラグは全セグメントの合成に成功した場合はTrue、失敗した場合はFalse。
    :rtype: `tuple[bool, list[str]]`
    """
    del outfile  # File assembly is centrally handled by tktts.py.
    speakers = speakers or {}
    tmpfiles = []
    rate = _normalize_prosody(getattr(cfg, "edge_rate", "+0%"))
    volume = _normalize_prosody(getattr(cfg, "edge_volume", "+0%"))
    pitch = _normalize_prosody(getattr(cfg, "edge_pitch", "+0Hz"), "+0Hz")

    print("\ntktts_edge.speak_dialogue():")
    index = 1
    for i, item in enumerate(dialogue or []):
        print(f"\nDialogue {i:04d}:")
        parts = split_dialogue(
            item,
            target_voices,
            speakers=speakers,
            default_voice=DEFAULT_EDGE_VOICE,
            is_monologue=bool(getattr(cfg, "monologue", False)),
        )
        for speaker, text in parts:
            text = apply_replacements(text, replacements)
            if not str(text).strip():
                continue
            voice = _select_voice(target_voices, speaker)
            filename = f"tmp_{index:03d}.{ext}"
            tmpfile = os.path.join(temp_dir, filename) if temp_dir else filename
            print(f"  {index:04d}: speaker={speaker} (voice={voice}): {text}")
            if speak(tmpfile, text, voice, rate=rate, volume=volume, pitch=pitch) is None:
                return False, tmpfiles
            tmpfiles.append(tmpfile)
            index += 1

    return True, tmpfiles