"""LLM router: creates the appropriate LLM client based on provider config."""

from __future__ import annotations

import os

from bilgeai.core.exceptions import LLMError
from bilgeai.llm.base import LLMClient


def get_llm_client(
    provider: str,
    model: str,
    api_key_env: str = "",
    base_url: str | None = None,
) -> LLMClient:
    """Return a configured LLM client for the given provider.

    Raises LLMError if the client cannot be created.
    """
    from bilgeai.llm.remote import RemoteClient

    if provider == "local":
        if not base_url:
            base_url = "http://localhost:11434/v1"
        return RemoteClient(
            model=f"openai/{model}" if not model.startswith("openai/") else model,
            api_key_env=api_key_env,
            base_url=base_url,
            is_local=True,
        )

    # Cloud providers
    if not api_key_env:
        raise LLMError(
            f"API key environment variable not configured for provider '{provider}'.",
            suggestion="Run 'bilge init' to configure your API key.",
        )

    api_key = os.environ.get(api_key_env)
    if not api_key:
        raise LLMError(
            f"API key not found. Set {api_key_env} environment variable.",
            suggestion=f"export {api_key_env}=your-api-key-here",
        )

    return RemoteClient(
        model=model,
        api_key_env=api_key_env,
        base_url=base_url,
        is_local=False,
    )
