"""
概要:
    edge-ttsを用いてテキストを音声合成し再生するサンプルスクリプトです。

詳細説明:
    コマンドライン引数としてテキストまたはテキストファイルのパスを受け取り、
    edge-ttsを使用して音声を生成し、生成されたMP3ファイルをOSの既定のアプリで再生します。

関連リンク:
    edge_tts_sample_usage
"""

import sys
import os
import asyncio
import tempfile
import subprocess

import edge_tts


VOICE = "ja-JP-NanamiNeural"


async def speak(text):
    """
    概要:
        与えられたテキストを音声に変換し、一時ファイルとして保存した後に再生します。

    詳細説明:
        edge-ttsライブラリを使用して指定されたテキストの音声を生成します。
        音声は一時的なMP3ファイルに保存され、Windows、macOS、Linuxの環境に合わせて
        デフォルトのプレイヤーで再生されます。

    引数:
        :param text: 読み上げる対象のテキスト。
        :type text: str

    戻り値:
        :returns: なし。
        :rtype: None

    例外:
        :raises Exception: 音声ファイルの再生中にエラーが発生した場合にコンソールに出力します。
    """

    with tempfile.NamedTemporaryFile(
        suffix=".mp3",
        delete=False
    ) as f:

        mp3file = f.name

    communicate = edge_tts.Communicate(
        text=text,
        voice=VOICE
    )

    await communicate.save(mp3file)

    try:
        if sys.platform.startswith("win"):
            os.startfile(mp3file)

        elif sys.platform == "darwin":
            subprocess.run(["open", mp3file])

        else:
            subprocess.run(["xdg-open", mp3file])

    except Exception as e:
        print(e)


def main():
    """
    概要:
        コマンドライン引数を処理し、音声合成と再生を実行します。

    詳細説明:
        コマンドライン引数が1つ未満の場合は使い方を表示して終了します。
        引数が実在するファイルパスの場合はそのファイルの内容を読み込み、
        そうでない場合は引数そのものをテキストとして扱います。
        その後、speak関数を非同期実行して音声を再生します。

    戻り値:
        :returns: なし。
        :rtype: None
    """

    if len(sys.argv) < 2:
        print("Usage:")
        print('  python edge_read.py "こんにちは"')
        print("  python edge_read.py sample.txt")
        sys.exit(1)

    arg = sys.argv[1]

    #
    # 引数が実在するファイルなら内容を読む
    #
    if os.path.isfile(arg):

        print(f"Read text file: {arg}")

        with open(arg, encoding="utf-8") as f:
            text = f.read()

    #
    # そうでなければ引数自身を読む
    #
    else:

        print("Read text from command line")

        text = arg

    asyncio.run(speak(text))


if __name__ == "__main__":
    main()