# services/translation/google_translate.py
"""
Google Translation service implementation
"""
from typing import Optional, List
import html
from google.cloud import translate_v2 as translate
from google.oauth2 import service_account
from config.api_keys import APIKeyManager
from .base import TranslationService

class GoogleTranslateService(TranslationService):
    def __init__(self, credentials_file: Optional[str] = None):
        """
        Initialize Google Translate service
        
        Args:
            credentials_file: Path to Google service account credentials JSON file.
                            If None, will use API key from APIKeyManager.
        """
        if credentials_file:
            # Use service account credentials
            try:
                credentials = service_account.Credentials.from_service_account_file(credentials_file)
                self.client = translate.Client(credentials=credentials)
            except Exception as e:
                raise ValueError(f"Error initializing Google Translate with credentials: {e}")
        else:
            # Use API key
            api_key = APIKeyManager.get_google_key()
            if not api_key:
                raise ValueError("Google API key not found. Please set up your API keys.")
            self.client = translate.Client()

    def translate_text(self, text: str, target_language: str, source_language: Optional[str] = None) -> str:
        """
        Translate a single text.
        
        Args:
            text: Text to translate
            target_language: Target language code (e.g., 'es' for Spanish)
            source_language: Source language code. If None, will be auto-detected.
            
        Returns:
            Translated text
        """
        try:
            result = self.client.translate(
                text,
                target_language=target_language,
                source_language=source_language
            )
            return html.unescape(result["translatedText"])
        except Exception as e:
            raise ValueError(f"Error in Google Translate: {e}")

    def translate_batch(self, texts: List[str], target_language: str, source_language: Optional[str] = None) -> List[str]:
        """
        Translate multiple texts in batch.
        
        Args:
            texts: List of texts to translate
            target_language: Target language code (e.g., 'es' for Spanish)
            source_language: Source language code. If None, will be auto-detected.
            
        Returns:
            List of translated texts
        """
        try:
            results = self.client.translate(
                texts,
                target_language=target_language,
                source_language=source_language
            )
            return [html.unescape(result["translatedText"]) for result in results]
        except Exception as e:
            raise ValueError(f"Error in Google Translate batch: {e}")