"""Carga (y cachea) el modelo MarianMT para traduccion ES -> EN."""

from __future__ import annotations

from typing import Any

# Cache global: model_name -> (tokenizer, model)
_MODEL_CACHE: dict[str, tuple[Any, Any]] = {}


def marianmt_es_en_load_model(
    model_name: str = "Helsinki-NLP/opus-mt-es-en",
) -> tuple[Any, Any]:
    """Loads (and caches) a MarianMT model for Spanish-to-English translation.

    MarianMT is a lightweight seq2seq translation model (~300 MB) from
    Helsinki-NLP, trained on the OPUS parallel corpus.

    LICENSE: Apache 2.0 — commercial use permitted.

    The first call downloads the model from HuggingFace Hub (~300 MB).
    Subsequent calls with the same ``model_name`` return the cached instance.

    Args:
        model_name: HuggingFace Hub model ID. Default is the ES->EN model.
            Other available models follow the pattern
            ``Helsinki-NLP/opus-mt-{src}-{tgt}``.

    Returns:
        Tuple ``(tokenizer, model)`` both ready for inference with
        ``model.generate(...)`` and ``tokenizer.decode(...)``.

    Raises:
        ImportError: if ``transformers`` is not installed.
        OSError: if the model cannot be downloaded or loaded from disk.
    """
    cached = _MODEL_CACHE.get(model_name)
    if cached is not None:
        return cached

    try:
        from transformers import MarianMTModel, MarianTokenizer
    except ImportError as exc:
        raise ImportError(
            "transformers no esta instalado. Instalalo con "
            "`uv pip install transformers` o `uv pip install -e '.[nlp]'`."
        ) from exc

    tokenizer = MarianTokenizer.from_pretrained(model_name)
    model = MarianMTModel.from_pretrained(model_name)
    model.eval()

    _MODEL_CACHE[model_name] = (tokenizer, model)
    return tokenizer, model
