"""Google Cloud Translation backend for pretok."""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Any

from pretok.translation.base import BaseTranslator, TranslationError, TranslationResult

if TYPE_CHECKING:
    from collections.abc import Sequence

    from pretok.config import GoogleTranslatorConfig

logger = logging.getLogger(__name__)


class GoogleTranslator(BaseTranslator):
    """Translator using Google Cloud Translation API v3.

    Requires the ``google-cloud-translate`` package::

        pip install pretok[google]

    Example:
        >>> from pretok.config import GoogleTranslatorConfig
        >>> config = GoogleTranslatorConfig(project_id="my-project")
        >>> translator = GoogleTranslator(config)
        >>> result = translator.translate("Hello", "zh")
        >>> result.translated_text
        '你好'
    """

    def __init__(self, config: GoogleTranslatorConfig) -> None:
        """Initialize Google Cloud Translation translator.

        Args:
            config: Google translator configuration

        Raises:
            ImportError: If google-cloud-translate package is not installed
            TranslationError: If configuration is invalid
        """
        try:
            from google.cloud import translate_v3 as translate
        except ImportError as e:
            msg = (
                "google-cloud-translate package is required for GoogleTranslator. "
                "Install it with: pip install google-cloud-translate"
            )
            raise ImportError(msg) from e

        self._config = config

        client_kwargs: dict[str, Any] = {}
        if config.credentials_path:
            from google.oauth2 import service_account

            credentials = service_account.Credentials.from_service_account_file(
                config.credentials_path
            )
            client_kwargs["credentials"] = credentials

        self._client = translate.TranslationServiceClient(**client_kwargs)

        if not config.project_id:
            raise TranslationError(
                "Google Cloud project_id is required",
                translator=self.name,
            )

        self._parent = f"projects/{config.project_id}/locations/{config.location}"

        logger.info(
            "Initialized GoogleTranslator: project=%s, location=%s",
            config.project_id,
            config.location,
        )

    @property
    def name(self) -> str:
        """Return translator name."""
        return "google"

    @property
    def supported_languages(self) -> list[str]:
        """Return supported languages (Google supports 100+ languages)."""
        return []

    def translate(
        self,
        text: str,
        target_language: str,
        source_language: str | None = None,
    ) -> TranslationResult:
        """Translate text using Google Cloud Translation.

        Args:
            text: Text to translate
            target_language: Target language code
            source_language: Source language code (optional)

        Returns:
            TranslationResult with translated text
        """
        if not text or not text.strip():
            return TranslationResult(
                source_text=text,
                translated_text=text,
                source_language=source_language or "unknown",
                target_language=target_language,
                translator=self.name,
            )

        try:
            request = {
                "parent": self._parent,
                "contents": [text],
                "target_language_code": target_language,
                "mime_type": "text/plain",
            }

            if source_language:
                request["source_language_code"] = source_language

            response = self._client.translate_text(request=request)
            translated_text = response.translations[0].translated_text

            detected_language = (
                source_language if source_language
                else response.translations[0].detected_language_code
            )

            return TranslationResult(
                source_text=text,
                translated_text=translated_text,
                source_language=detected_language or "auto",
                target_language=target_language,
                translator=self.name,
                metadata={
                    "model": getattr(response.translations[0], "model", ""),
                },
            )

        except Exception as e:
            raise TranslationError(
                f"Google translation failed: {e}",
                source_text=text,
                source_language=source_language,
                target_language=target_language,
                translator=self.name,
                cause=e,
            ) from e

    def translate_batch(
        self,
        texts: Sequence[str],
        target_language: str,
        source_language: str | None = None,
    ) -> list[TranslationResult]:
        """Translate multiple texts using Google Cloud Translation.

        Google's API natively supports batch translation.
        """
        if not texts:
            return []

        try:
            request: dict[str, Any] = {
                "parent": self._parent,
                "contents": list(texts),
                "target_language_code": target_language,
                "mime_type": "text/plain",
            }

            if source_language:
                request["source_language_code"] = source_language

            response = self._client.translate_text(request=request)

            results = []
            for i, translation in enumerate(response.translations):
                detected = (
                    source_language if source_language
                    else translation.detected_language_code
                )
                results.append(
                    TranslationResult(
                        source_text=texts[i],
                        translated_text=translation.translated_text,
                        source_language=detected or "auto",
                        target_language=target_language,
                        translator=self.name,
                    )
                )
            return results

        except Exception:
            logger.warning("Batch translation failed, falling back to individual translations")
            return [self.translate(text, target_language, source_language) for text in texts]
