"""Model selection delegated to llx."""

from typing import Any, Dict, List, Optional

try:
    from llx import select_model, LlxConfig
    from llx.analysis.collector import ProjectMetrics
    from llx.litellm_config import LiteLLMConfig
    LLX_AVAILABLE = True
except ImportError:
    LLX_AVAILABLE = False
    # Fallback implementations
    def select_model(*args, **kwargs):
        return "claude-sonnet-4-20250514"
    
    class LlxConfig:
        @staticmethod
        def load():
            return LlxConfig()
        
        def __init__(self):
            self.models = {
                "balanced": type("Model", (), {"model_id": "claude-sonnet-4-20250514"})()
            }
    
    class ProjectMetrics:
        pass
    
    class LiteLLMConfig:
        @staticmethod
        def load():
            return LiteLLMConfig()
        
        def __init__(self):
            self.model_list = []
        
        def get_models_by_tier(self, tier):
            return []
        
        def resolve_alias(self, model_str):
            return model_str


def get_best_available_model(task_tier="balanced"):
    """Get the best available model for the given task tier."""
    if not LLX_AVAILABLE:
        return "claude-sonnet-4-20250514"
    
    tier_map = {
        "simple": "cheap", 
        "standard": "balanced", 
        "complex": "premium",
        "trivial": "cheap",
        "operational": "cheap",
        "deep": "premium"
    }
    
    try:
        config = LlxConfig.load()
        model = config.models.get(tier_map.get(task_tier, "balanced"))
        return model.model_id if model else "claude-sonnet-4-20250514"
    except Exception:
        return "claude-sonnet-4-20250514"


def filter_models(tier=None, provider=None, **kw) -> List[Dict[str, Any]]:
    """Filter models by tier and/or provider."""
    if not LLX_AVAILABLE:
        return []
    
    try:
        lc = LiteLLMConfig.load()
        models = lc.get_models_by_tier(tier) if tier else lc.model_list
        if provider:
            models = [m for m in models if m.provider == provider]
        return [{"model_id": m.model_id, "provider": m.provider} for m in models]
    except Exception:
        return []


def resolve_model(model_str: str) -> str:
    """Resolve model alias to actual model ID."""
    if not LLX_AVAILABLE:
        return model_str
    
    try:
        return LiteLLMConfig.load().resolve_alias(model_str)
    except Exception:
        return model_str


def analyze_project_metrics(project_path: str) -> Optional[ProjectMetrics]:
    """Analyze project metrics using llx."""
    if not LLX_AVAILABLE:
        return None
    
    try:
        from llx import analyze_project
        return analyze_project(project_path)
    except Exception:
        return None
