"""Tests para detect_corpus_language."""

import builtins
import os
import sys

# Anade python/functions a sys.path para importar el paquete `datascience`.
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from datascience.detect_corpus_language import detect_corpus_language

_ES = [
    "este es un texto bastante largo en español para detectar el idioma correctamente sin problemas",
    "la inteligencia artificial transforma la manera en que trabajamos cada dia en muchos sectores",
]
_EN = [
    "this is a fairly long english text to detect the language correctly without any length issues",
    "machine learning models can classify documents into many different categories quite reliably",
]


def test_mixto_es_en():
    """Golden: corpus mixto ES+EN claro -> available True, >=2 idiomas, counts coherentes."""
    out = detect_corpus_language(_ES + _EN)
    assert out["available"] is True
    assert out["dominant"] in {"es", "en"}
    assert len(out["distribution"]) >= 2
    total = sum(item["count"] for item in out["distribution"])
    assert total == out["n_detected"]
    assert out["n_detected"] == 4


def test_vacio():
    """Edge: lista vacia con langdetect presente -> available True, sin detecciones."""
    out = detect_corpus_language([])
    assert out["available"] is True
    assert out["n_detected"] == 0
    assert out["distribution"] == []
    assert out["dominant"] is None


def test_degradacion(monkeypatch):
    """Error path: si langdetect no es importable -> degrada a available False sin lanzar."""
    import datascience.detect_corpus_language as m

    real_import = builtins.__import__

    def fake_import(name, *a, **k):
        if name == "langdetect" or name.startswith("langdetect."):
            raise ImportError("simulado")
        return real_import(name, *a, **k)

    monkeypatch.setattr(builtins, "__import__", fake_import)
    out = m.detect_corpus_language(["hola mundo", "hello world"])
    assert out["available"] is False
    assert out["n_detected"] == 0
    assert out["distribution"] == []
    assert out["dominant"] is None
