"""Language detection for multilingual routing."""

from __future__ import annotations

import logging

logger = logging.getLogger("ecate.language")

# Lazy-loaded detector
_detector = None


def _get_detector():
    """Lazy-load language detector."""
    global _detector
    if _detector is not None:
        return _detector
    
    try:
        from langdetect import detect, DetectorFactory
        # Make detection deterministic
        DetectorFactory.seed = 0
        _detector = detect
        logger.debug("Using langdetect for language detection")
        return _detector
    except ImportError:
        logger.warning(
            "langdetect not installed — language detection disabled. "
            "Install with: pip install langdetect"
        )
        return None


def detect_language(text: str) -> str | None:
    """Detect language from text.
    
    Returns:
        ISO 639-1 language code (e.g., 'en', 'it', 'fr', 'de') or None if
        detection is unavailable or text is too short.
    
    When langdetect is not installed, returns None (all models considered).
    """
    if not text or len(text) < 10:
        return None
    
    detector = _get_detector()
    if detector is None:
        return None
    
    try:
        return detector(text)
    except Exception as e:
        logger.debug(f"Language detection failed: {e}")
        return None


def is_language_supported(detected: str | None, supported: list[str] | None) -> bool:
    """Check if detected language is in the model's supported list.
    
    Args:
        detected: Detected language code (e.g., 'en') or None
        supported: Model's supported_languages list or None (= all)
    
    Returns:
        True if the model should be considered for this language.
    """
    # Model supports all languages
    if supported is None:
        return True
    
    # Detection unavailable — include model to be safe
    if detected is None:
        return True
    
    return detected in supported
