""" 参数 Adapters for AI Service Providers

This module provides the base adapter interface and registry for parameter
transformation. Each provider implements its own adapter in its respective
directory (e.g., dashscope/adapter.py, volcengine/adapter.py).

Usage:
    from src.services.provider.adapters import get_adapter, register_adapter
    
    adapter = get_adapter('dashscope')
    provider_params = adapter.adapt_generate_params(standard_params)
"""

from abc import ABC, abstractmethod
from typing import Dict, Any, Optional, Type
import logging

from src.services.provider.base import ServiceResponse, TaskStatus, GenerationResult

logger = logging.getLogger(__name__)


class ParameterAdapter(ABC):
    """Base class for parameter adapters.
    
    Each provider should implement a concrete adapter that transforms
    standard parameters into the provider's expected format.
    
    Subclasses should be placed in their respective provider directories:
    - dashscope/adapter.py
    - volcengine/adapter.py
    - modelscope/adapter.py
    """
    provider_name: str = "base"
    
    @abstractmethod
    def adapt_generate_params(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """Convert standard parameters to provider-specific format.
        
        Args:
            params: Standard parameters dictionary
            
        Returns:
            Provider-specific parameters dictionary
        """
        pass
    
    @abstractmethod
    def adapt_response(self, raw_response: Dict[str, Any]) -> ServiceResponse:
        """Convert provider response to standard ServiceResponse.
        
        Args:
            raw_response: Raw response from provider API
            
        Returns:
            Standard ServiceResponse object
        """
        pass
    
    def get_actual_model(self, base_model: str, params: Dict[str, Any], variants: Optional[Dict[str, str]] = None) -> str:
        """Determine the actual model variant to use based on parameters.
        
        Args:
            base_model: Base model name
            params: Request parameters
            variants: Model variants mapping (e.g., {"t2v": "model-t2v", "i2v": "model-i2v"})
            
        Returns:
            Actual model name to use
        """
        if not variants:
            return base_model
        return base_model


# 适配器 Registry - populated by provider adapters on import
_ADAPTER_REGISTRY: Dict[str, Type[ParameterAdapter]] = {}


def get_adapter(provider: str) -> Optional[ParameterAdapter]:
    """ 获取 adapter instance for a provider.
    
    Args:
        provider: Provider name (e.g., 'dashscope', 'volcengine')
        
    Returns:
        Adapter instance or None if not found
    """
    # Lazy import provider adapters if not already registered
    if not _ADAPTER_REGISTRY:
        _load_provider_adapters()
    
    adapter_class = _ADAPTER_REGISTRY.get(provider.lower())
    if adapter_class:
        return adapter_class()
    return None


def register_adapter(provider: str, adapter_class: Type[ParameterAdapter]):
    """Register a new adapter for a provider.
    
    Args:
        provider: Provider name
        adapter_class: Adapter class to register
    """
    _ADAPTER_REGISTRY[provider.lower()] = adapter_class
    logger.info(f"Registered adapter for provider: {provider}")


def _load_provider_adapters():
    """Lazy load all provider adapters."""
    try:
        from src.services.provider.dashscope.adapter import DashScopeVideoAdapter
        register_adapter("dashscope", DashScopeVideoAdapter)
    except ImportError as e:
        logger.debug(f"DashScope adapter not available: {e}")
    
    try:
        from src.services.provider.volcengine.adapter import VolcengineVideoAdapter
        register_adapter("volcengine", VolcengineVideoAdapter)
    except ImportError as e:
        logger.debug(f"Volcengine adapter not available: {e}")
    
    try:
        from src.services.provider.modelscope.adapter import ModelScopeVideoAdapter
        register_adapter("modelscope", ModelScopeVideoAdapter)
    except ImportError as e:
        logger.debug(f"ModelScope adapter not available: {e}")


def list_adapters() -> Dict[str, Type[ParameterAdapter]]:
    """ 列表 all registered adapters.
    
    Returns:
        Dictionary of provider name to adapter class
    """
    if not _ADAPTER_REGISTRY:
        _load_provider_adapters()
    return _ADAPTER_REGISTRY.copy()
