"""LangChain chat model factory — replaces llm/factory.py."""
from __future__ import annotations

from typing import Any

from langchain_core.language_models import BaseChatModel

from claim_validator.exceptions import ConfigurationError


def build_chat_model(config: dict[str, Any]) -> BaseChatModel:
    """Create a LangChain chat model from provider config."""
    provider = config["provider"]
    common: dict[str, Any] = {
        "model": config["model"],
        "api_key": config.get("api_key", ""),
        "temperature": config.get("temperature", 0.0),
        "max_tokens": config.get("max_tokens", 4096),
        "timeout": config.get("timeout", 30),
    }

    match provider:
        case "groq":
            from langchain_groq import ChatGroq
            return ChatGroq(**common)
        case "openai":
            from langchain_openai import ChatOpenAI
            return ChatOpenAI(**common)
        case "openai_compatible":
            from langchain_openai import ChatOpenAI
            return ChatOpenAI(base_url=config["base_url"], **common)
        case "anthropic":
            from langchain_anthropic import ChatAnthropic
            return ChatAnthropic(**common)
        case _:
            raise ConfigurationError(
                f"Unknown LLM provider: {provider!r}. "
                f"Supported: 'anthropic', 'openai', 'openai_compatible', 'groq'."
            )
