import os
from google.cloud import texttospeech

# 認証キーのパス設定
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/key/libertycall-main-7e4af202cdff.json"

# Google Cloud TTSクライアントの初期化
client = texttospeech.TextToSpeechClient()

# 音声生成する内容
PHRASES = [
    ("お電話ありがとうございます。", "lp/demo_1_greeting.mp3"),
    ("でございます。", "lp/demo_2_request.mp3"),
    ("AIオペレーターがご対応させて戴きます。", "lp/demo_3_operator.mp3"),
    ("ご用件をどうぞ。", "lp/demo_4_request.mp3"),
]

def synth(text: str, out_path: str) -> None:
    synthesis_input = texttospeech.SynthesisInput(text=text)
    try:
        response = client.synthesize_speech(
            request={
                "input": synthesis_input,
                "voice": voice,
                "audio_config": audio_config,
            }
        )
        os.makedirs(os.path.dirname(out_path), exist_ok=True)
        with open(out_path, "wb") as f:
            f.write(response.audio_content)
        print(f"[OK] generated: {out_path}")
    except Exception as e:
        print(f"[ERROR] failed to generate {out_path}: {e}")
        # 詳細なエラーメッセージを表示
        if hasattr(e, 'message'):
            print(f"[ERROR] Message: {e.message}")
        elif hasattr(e, 'args') and e.args:
            print(f"[ERROR] Args: {e.args}")
        else:
            print("[ERROR] No additional error message available")
        response = client.synthesize_speech(
            request={
                "input": synthesis_input,
                "voice": voice,
                "audio_config": audio_config,
            }
        )
        
        # 出力先のディレクトリを作成
        os.makedirs(os.path.dirname(out_path), exist_ok=True)
        
        # 音声データを書き込み
        with open(out_path, "wb") as f:
            f.write(response.audio_content)
        
        print(f"[OK] generated: {out_path}")
    
    except Exception as e:
        # エラーが発生した場合、エラーメッセージを詳細に表示
        print(f"[ERROR] failed to generate {out_path}: {e}")
        if hasattr(e, 'message'):
            print(f"[ERROR] Message: {e.message}")
        else:
            print("[ERROR] No additional error message available")

def main():
    # 定義されたフレーズを音声化
    for text, path in PHRASES:
        synth(text, path)

if __name__ == "__main__":
    main()
