from typing import TYPE_CHECKING

from yera.models.llm_context import LLMContext
from yera.models.llm_interfaces.interface_registry import get_interface

if TYPE_CHECKING:
    from yera.config2.dataclasses import LLMConfig


class LLMContextFactory:
    def __init__(self, model_cfg: "LLMConfig", creds_map: dict[str, str]):
        from yera.config2.dataclasses import LLMConfig

        if not isinstance(model_cfg, LLMConfig):
            raise TypeError(
                f"model_cfg must be type LLMConfig. Was {type(model_cfg).__name__}."
            )

        self.model_cfg = model_cfg
        self.creds_map = creds_map

    def __call__(self, **kwargs) -> LLMContext:
        self.llm_cls = get_interface(self.model_cfg.interface)
        if self.llm_cls is None:
            raise ValueError(
                f"Could not find llm interface class '{self.model_cfg.interface}'"
            )

        # todo: metaclass magic for runtime signature generation from config
        interface = self.llm_cls(self.model_cfg, kwargs, creds_map=self.creds_map)

        return LLMContext(
            interface=interface,
        )
