"""Factory for creating LLM providers."""

import os
from typing import Union

from .base import LLMProvider
from .models import ModelRegistry, ModelEntry
from .openai_provider import OpenAIProvider


# ═══════════════════════════════════════════════════════════════════════════════
# Configuration - Single source of truth
# ═══════════════════════════════════════════════════════════════════════════════

def _get_default_model_name() -> str:
    """Get default model name from env or registry."""
    env_model = os.environ.get("EMDASH_MODEL") or os.environ.get("EMDASH_DEFAULT_MODEL")
    if env_model:
        return env_model
    return ModelRegistry.get().default_model


def _get_vision_model_name() -> str:
    """Get vision model name from env or registry."""
    env_model = os.environ.get("EMDASH_VISION_MODEL")
    if env_model:
        return env_model
    return ModelRegistry.get().vision_model


# Module-level constants for backward compatibility
DEFAULT_MODEL = _get_default_model_name()
VISION_MODEL = _get_vision_model_name()

# Default API key environment variable (used by default model)
DEFAULT_API_KEY_ENV = "FIREWORKS_API_KEY"


# ═══════════════════════════════════════════════════════════════════════════════
# Factory functions
# ═══════════════════════════════════════════════════════════════════════════════


def get_provider(model: Union[str, ModelEntry, None] = None) -> LLMProvider:
    """
    Get an LLM provider for the specified model.

    Uses OpenAI SDK with provider-specific base URLs.

    Args:
        model: ModelEntry, model name/alias, or None for default model.
            Examples:
                - "minimax", "kimi", "glm-4p7"
                - "fireworks:accounts/fireworks/models/minimax-m2p1"

    Returns:
        LLMProvider instance
    """
    if model is None:
        model = _get_default_model_name()

    if isinstance(model, ModelEntry):
        return OpenAIProvider(model)

    # Try to look up in registry
    registry = ModelRegistry.get()
    entry = registry.get_model(model)
    if entry:
        return OpenAIProvider(entry)

    # Assume it's a raw model string
    return OpenAIProvider(model)


def get_default_model() -> ModelEntry:
    """Get the default model."""
    return ModelRegistry.get().get_default()


def get_default_api_key() -> str | None:
    """Get the default API key from environment."""
    return os.environ.get(DEFAULT_API_KEY_ENV)


def list_available_models() -> list[dict]:
    """List all available models."""
    return ModelRegistry.get().list_all()


def get_vision_provider() -> LLMProvider:
    """Get a vision-capable LLM provider.

    Uses EMDASH_VISION_MODEL env var or registry default.

    Returns:
        LLMProvider instance that supports vision
    """
    return get_provider(_get_vision_model_name())


def get_vision_model() -> str:
    """Get the configured vision model name.

    Returns:
        Vision model string from EMDASH_VISION_MODEL or registry default
    """
    return _get_vision_model_name()
