<?php

class GoogleTTSService
{
    private string $apiKey;
    private string $endpoint = 'https://texttospeech.googleapis.com/v1/text:synthesize';
    
    // Voice mapping for different languages
    private array $voiceMap = [
        'fr-FR' => ['name' => 'fr-FR-Neural2-A', 'gender' => 'FEMALE'],
        'fr' => ['name' => 'fr-FR-Neural2-A', 'gender' => 'FEMALE'],
        'en-US' => ['name' => 'en-US-Neural2-F', 'gender' => 'FEMALE'],
        'en' => ['name' => 'en-US-Neural2-F', 'gender' => 'FEMALE'],
        'en-GB' => ['name' => 'en-GB-Neural2-A', 'gender' => 'FEMALE'],
        'ar' => ['name' => 'ar-XA-Wavenet-A', 'gender' => 'FEMALE'],
        'es' => ['name' => 'es-ES-Neural2-A', 'gender' => 'FEMALE'],
        'pt' => ['name' => 'pt-BR-Neural2-A', 'gender' => 'FEMALE'],
        'de' => ['name' => 'de-DE-Neural2-A', 'gender' => 'FEMALE'],
        // For unsupported languages, fallback to French
        'bm' => ['name' => 'fr-FR-Neural2-A', 'gender' => 'FEMALE'], // Bambara -> French fallback
        'ff' => ['name' => 'fr-FR-Neural2-A', 'gender' => 'FEMALE'], // Fulah -> French fallback
        'snk' => ['name' => 'fr-FR-Neural2-A', 'gender' => 'FEMALE'], // Soninke -> French fallback
    ];
    
    public function __construct()
    {
        $this->apiKey = defined('GOOGLE_TTS_API_KEY') ? GOOGLE_TTS_API_KEY : '';
    }
    
    public function isConfigured(): bool
    {
        return !empty($this->apiKey);
    }
    
    public function synthesize(string $text, string $languageCode = 'fr-FR'): ?string
    {
        if (!$this->isConfigured()) {
            return null;
        }
        
        // Get voice configuration
        $voiceConfig = $this->voiceMap[$languageCode] ?? $this->voiceMap['fr-FR'];
        $langCode = $this->getLanguageCode($languageCode);
        
        $requestBody = [
            'input' => [
                'text' => $text
            ],
            'voice' => [
                'languageCode' => $langCode,
                'name' => $voiceConfig['name'],
                'ssmlGender' => $voiceConfig['gender']
            ],
            'audioConfig' => [
                'audioEncoding' => 'MP3',
                'pitch' => 0.5,           // Slightly higher for warmth
                'speakingRate' => 0.95,   // Slightly slower for clarity
                'effectsProfileId' => ['small-bluetooth-speaker-class-device']
            ]
        ];
        
        $ch = curl_init($this->endpoint . '?key=' . $this->apiKey);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json'
            ],
            CURLOPT_POSTFIELDS => json_encode($requestBody),
            CURLOPT_TIMEOUT => 30
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode !== 200) {
            error_log('Google TTS Error: ' . $response);
            return null;
        }
        
        $data = json_decode($response, true);
        
        if (isset($data['audioContent'])) {
            return $data['audioContent']; // Base64 encoded MP3
        }
        
        return null;
    }
    
    private function getLanguageCode(string $code): string
    {
        $mapping = [
            'fr' => 'fr-FR',
            'en' => 'en-US',
            'ar' => 'ar-XA',
            'es' => 'es-ES',
            'pt' => 'pt-BR',
            'de' => 'de-DE',
            'bm' => 'fr-FR',
            'ff' => 'fr-FR',
            'snk' => 'fr-FR',
        ];
        
        return $mapping[$code] ?? $code;
    }
    
    public function getAvailableVoices(): array
    {
        return array_keys($this->voiceMap);
    }
}
