import logging
from typing import Dict, Optional

from llm_sdk.model_providers.azure_openai import (
    AzureOpenAIEmbeddingModel,
    AzureOpenAILargeLanguageModel,
)
from llm_sdk.model_providers.base import AIModel, ConfigType
from llm_sdk.model_providers.deepseek import DeepseekLargeLanguageModel
from llm_sdk.model_providers.ollama import (
    OllamaEmbeddingModel,
    OllamaLargeLanguageModel,
)
from llm_sdk.model_providers.openai_api_compatible import (
    OAIAPICompatEmbeddingModel,
    OAIAPICompatLargeLanguageModel,
    OAICompatRerankModel,
)
from llm_sdk.model_providers.tongyi import (
    GTERerankModel,
    TongyiLargeLanguageModel,
    TongyiTextEmbeddingModel,
)
from llm_sdk.model_providers.xinference import (
    XinferenceAILargeLanguageModel,
    XinferenceRerankModel,
    XinferenceTextEmbeddingModel,
)

logger = logging.getLogger(__name__)


class ModelProviderFactory:

    @staticmethod
    def build_provider_model(
        model_provider: str,
        model_name: str,
        config_type: ConfigType = ConfigType.CHAT,
        crendential: Optional[Dict] = None,
        app_id: Optional[str] = None,
    ) -> Optional[AIModel]:
        provider_map = {
            "azure_openai": {
                ConfigType.CHAT: AzureOpenAILargeLanguageModel,
                ConfigType.EMBEDDING: AzureOpenAIEmbeddingModel,
            },
            "xinference": {
                ConfigType.CHAT: XinferenceAILargeLanguageModel,
                ConfigType.EMBEDDING: XinferenceTextEmbeddingModel,
                ConfigType.RERANK: XinferenceRerankModel,
            },
            "tongyi": {
                ConfigType.CHAT: TongyiLargeLanguageModel,
                ConfigType.EMBEDDING: TongyiTextEmbeddingModel,
                ConfigType.RERANK: GTERerankModel,
            },
            "openai_api_compatible": {
                ConfigType.CHAT: OAIAPICompatLargeLanguageModel,
                ConfigType.EMBEDDING: OAIAPICompatEmbeddingModel,
                ConfigType.RERANK: OAICompatRerankModel,
            },
            "ollama": {
                ConfigType.CHAT: OllamaLargeLanguageModel,
                ConfigType.EMBEDDING: OllamaEmbeddingModel,
            },
            "deepseek": {
                ConfigType.CHAT: DeepseekLargeLanguageModel,
            },
        }
        provider = provider_map.get(model_provider)
        if provider:
            model_class = provider.get(config_type)
            if model_class:
                return model_class(model_name, crendential, app_id)
            else:
                raise ValueError(f"Model class not found for {model_provider} and {config_type}")
        else:
            raise ValueError(f"Provider not found for {model_provider}")
