"""
LLM interface for the Metis Agent Framework.
Provides a unified interface to multiple LLM providers.
"""
from typing import Optional, Dict, Any, List
from ..llm.factory import LLMFactory
from ..llm.base import BaseLLM
from ..auth.api_key_manager import APIKeyManager

# Global LLM instance
_llm_instance = None

def configure_llm(
    provider: str, 
    model: Optional[str] = None,
    api_key: Optional[str] = None,
    **kwargs
):
    """
    Configure the global LLM instance.
    
    Args:
        provider: LLM provider name
        model: Model name
        api_key: API key
        **kwargs: Additional arguments for the LLM
    """
    global _llm_instance
    _llm_instance = LLMFactory.create(provider, model, api_key, **kwargs)
    
def get_llm() -> BaseLLM:
    """
    Get the global LLM instance.
    If not configured, tries to create one using available API keys.
    
    Returns:
        LLM instance
    """
    global _llm_instance
    
    if _llm_instance is None:
        # Try to create an LLM using available API keys
        key_manager = APIKeyManager()
        
        # Try providers in order of preference (Groq first as default)
        for provider in ["groq", "anthropic", "huggingface", "openai"]:
            if key_manager.has_key(provider):
                try:
                    _llm_instance = LLMFactory.create(provider)
                    break
                except Exception as e:
                    print(f"Warning: Could not create {provider} LLM: {e}")
                    
        if _llm_instance is None:
            # Fall back to Groq with a default API key for testing
            try:
                from ..llm.groq_llm import GroqLLM
                _llm_instance = GroqLLM(
                    model="llama3-70b-8192",
                    api_key="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"
                )
                print("- Using fallback Groq LLM with default API key. Please configure a proper API key.")
            except Exception as e:
                raise ValueError(f"No LLM configured and could not create fallback: {e}")
            
    return _llm_instance