from ..base_gcp_agent import BaseGCPAgent
from ..gcp_connector import GCPConnector
from google.cloud import texttospeech

class TextToSpeechAgent(BaseGCPAgent):
    """
    An agent specialized in handling GCP Cloud Text-to-Speech tasks.
    """

    def execute(self, command: str, **kwargs):
        """
        Executes a given command related to Text-to-Speech.
        """
        if command == 'synthesize_speech':
            return self._synthesize_speech(**kwargs)
        else:
            raise NotImplementedError(f"Command '{command}' is not supported by TextToSpeechAgent.")

    def _synthesize_speech(self, project_id: str, text: str, output_file: str = 'output.mp3', language_code: str = 'en-US', ssml_gender: str = 'NEUTRAL'):
        """
        Synthesizes speech from a given text and saves the audio output to a local file.
        """
        print(f"TextToSpeechAgent: Synthesizing speech for text in project '{project_id}' and saving to '{output_file}'...")
        try:
            client = texttospeech.TextToSpeechClient(credentials=GCPConnector.get_credentials())

            synthesis_input = texttospeech.SynthesisInput(text=text)

            voice = texttospeech.VoiceSelectionParams(
                language_code=language_code,
                ssml_gender=texttospeech.SsmlVoiceGender[ssml_gender]
            )

            audio_config = texttospeech.AudioConfig(
                audio_encoding=texttospeech.AudioEncoding.MP3
            )

            response = client.synthesize_speech(
                input=synthesis_input,
                voice=voice,
                audio_config=audio_config
            )

            with open(output_file, 'wb') as out:
                out.write(response.audio_content)
                print(f'Audio content written to file "{output_file}" ')

            return {"status": "success", "message": f"Speech synthesized and saved to '{output_file}'.", "output_file": output_file}
        except Exception as e:
            print(f"Error synthesizing speech: {e}")
            return {"status": "error", "message": str(e)}
