"""Single cached default LLM instance from flat LLM_* / NORMBASE_LLM_* env."""
from __future__ import annotations

import functools

from llm.providers import BaseLLMProvider, create_provider
from llm.settings import LLMSettings, settings_to_provider_block


@functools.lru_cache(maxsize=1)
def _cached_default_llm_provider() -> BaseLLMProvider:
    s = LLMSettings()
    block = settings_to_provider_block(s)
    p = create_provider(s.llm_provider.strip(), block)
    if p is None:
        raise RuntimeError(
            f"Could not construct LLM provider {s.llm_provider!r}. "
            "Check LLM_PROVIDER and related env vars."
        )
    return p


def get_default_llm_provider() -> BaseLLMProvider:
    """Process-wide default LLM (Normbase retrieval, extraction, scripts)."""
    return _cached_default_llm_provider()


def clear_llm_provider_cache() -> None:
    """Clear cached instance (tests or after env change)."""
    _cached_default_llm_provider.cache_clear()
