"""Language detection for element text. Optional dependency: langdetect."""

from __future__ import annotations

_AVAILABLE = False
try:
    from langdetect import DetectorFactory
    from langdetect import detect as _ld_detect

    DetectorFactory.seed = 0  # reproducible results
    _AVAILABLE = True
except ImportError:
    pass

# CJK and Arabic scripts need smaller token budgets with cl100k_base
# (more characters per concept than Latin scripts)
_BUDGET_SCALE: dict[str, float] = {
    "zh-cn": 0.5,
    "zh-tw": 0.5,
    "zh": 0.5,
    "ja": 0.5,
    "ko": 0.5,
    "ar": 0.7,
    "fa": 0.7,
    "he": 0.8,
    "th": 0.7,
}


def detect(text: str, min_chars: int = 50) -> str | None:
    """Detect BCP-47 language tag. Returns None if detection unavailable or text too short."""
    if not _AVAILABLE or len(text) < min_chars:
        return None
    try:
        return _ld_detect(text)  # type: ignore[no-untyped-call]
    except Exception:
        return None


def is_available() -> bool:
    return _AVAILABLE


def token_budget_scale(lang: str | None) -> float:
    """Return a scale factor (0-1) to apply to the chunk token budget for this language."""
    if lang is None:
        return 1.0
    return _BUDGET_SCALE.get(lang, 1.0)
