"""Carga (y cachea) un modelo spaCy en castellano para NER y OpenIE.

LICENSE: spaCy = MIT. Modelo es_core_news_md = CC BY-SA 4.0 (datos CoNLL-2002).
"""

from __future__ import annotations

from typing import Any

# Cache global: model_name -> instancia spaCy nlp
_MODEL_CACHE: dict[str, Any] = {}


def spacy_es_load_model(model_name: str = "es_core_news_md") -> Any:
    """Load (and cache) a spaCy Spanish language model.

    The model provides dependency parsing, POS tagging and NER (PER, ORG, LOC, MISC).
    Used by extract_triples_spacy_es for schema-less OpenIE in Spanish.

    LICENSE: spaCy = MIT. es_core_news_md = CC BY-SA 4.0 (CoNLL-2002 corpus).

    Args:
        model_name: Name of the spaCy model. Default: es_core_news_md.
                    Alternatives: es_core_news_sm (smaller), es_core_news_lg (larger).

    Returns:
        spaCy Language instance cached by model_name.

    Raises:
        OSError: If the model is not installed. Install with:
                 python -m spacy download es_core_news_md
    """
    if model_name in _MODEL_CACHE:
        return _MODEL_CACHE[model_name]

    import spacy  # type: ignore[import]

    nlp = spacy.load(model_name)
    _MODEL_CACHE[model_name] = nlp
    return nlp
