from google import genai
from google.genai import types
client = genai.Client()

language_code_mapping = {
    "english": "en-US",
    "malayalam": "ml-IN",
    "hindi": "hi-IN",
    "tamil": "ta-IN",
    "telugu": "te-IN",
    "bengali": "bn-IN",
    "kannada": "kn-IN",
    "marathi": "mr-IN",
    "gujarati": "gu-IN",
    "punjabi": "pa-IN",
}

def gemini_tts(content: str, language: str = "english", voice: str = "Charon"):
    
    response = client.models.generate_content(
        model="gemini-2.5-flash-preview-tts",
        contents=content,
        config=types.GenerateContentConfig(
            response_modalities=["AUDIO"],
            speech_config=types.SpeechConfig(
                voice_config=types.VoiceConfig(
                    prebuilt_voice_config=types.PrebuiltVoiceConfig(
                    voice_name=voice,
                    
                    )
                ),
            )
        )
    )
    

    try:
        # 1. Check if a candidate exists
        if not response.candidates:
            print("❌ Error: No candidates found in response.")
            return None
        
        # 2. Access the deeply nested audio bytes
        audio_data = response.candidates[0].content.parts[0].inline_data.data
        
        # 3. Verify the MIME type (optional but good practice)
        if audio_data is not None:
            # Wrap the raw PCM bytes in a WAV container
            wav_bytes = wrap_pcm_to_wav(audio_data)
            return wav_bytes # Return the complete WAV bytes
        else:
            # Handle case where audio generation fails
            print("❌ Error: Audio data not found in response.")
            return None

    except (IndexError, AttributeError) as e:
        print(f"❌ Error: Failed to parse audio data from response structure. {e}")
        return None



import struct
import wave # Import the standard 'wave' module

def create_wav_header(pcm_data_length, channels=1, sample_rate=24000, bit_depth=16):
    """
    Creates a WAV header for raw PCM audio data.
    The Gemini TTS model returns 16-bit, 24kHz, mono PCM.
    """
    # 1. Calculate parameters
    byte_rate = sample_rate * channels * bit_depth // 8
    block_align = channels * bit_depth // 8
    chunk_size = 36 + pcm_data_length
    sub_chunk2_size = pcm_data_length

    # 2. Construct the header using little-endian byte order '<'
    wav_header = struct.pack(
        '<4sI4s'  # RIFF chunk descriptor: ChunkID, ChunkSize, Format
        '4sIHHIIHH'  # fmt sub-chunk: Subchunk1ID, Subchunk1Size, AudioFormat, NumChannels, SampleRate, ByteRate, BlockAlign, BitsPerSample
        '4sI',  # data sub-chunk: Subchunk2ID, Subchunk2Size
        b'RIFF', chunk_size, b'WAVE',
        b'fmt ', 16, 1, channels, sample_rate, byte_rate, block_align, bit_depth,
        b'data', sub_chunk2_size
    )
    return wav_header

def wrap_pcm_to_wav(pcm_data):
    """Combines WAV header and raw PCM data."""
    # Gemini TTS data is: 1 channel, 24000 Hz, 16 bits per sample
    header = create_wav_header(len(pcm_data))
    return header + pcm_data