"""Factory functions for creating LLM-powered agents."""

import asyncio
import anthropic
from ..config import Config


def create_key_rotator(api_keys):
    """Create a function that rotates through API keys.
    
    Args:
        api_keys: List of API keys to rotate through
        
    Returns:
        Function that returns the next API key in rotation
    """
    key_index = {"current": 0}
    
    def get_next_api_key():
        """Rotate through available API keys."""
        key = api_keys[key_index["current"]]
        key_index["current"] = (key_index["current"] + 1) % len(api_keys)
        return key
    
    return get_next_api_key


async def create_llm_function(api_key_func, system_prompt: str, temperature: float = None):
    """Factory function to create LLM-powered agent functions.
    
    Args:
        api_key_func: Function that returns an API key or the key itself
        system_prompt: System prompt defining the agent's role and behavior
        temperature: Temperature for LLM sampling (default from config)
        
    Returns:
        Async function that executes the agent logic
    """
    if temperature is None:
        temperature = Config.DEFAULT_TEMPERATURE
    
    # Create a new client for each call to rotate keys
    def get_client():
        key = api_key_func() if callable(api_key_func) else api_key_func
        return anthropic.Anthropic(api_key=key)
    
    async def llm_agent(context) -> str:
        """Execute agent logic using Anthropic Claude. Accepts a context dict from workspace engine."""
        # Get the task prompt from context dictionary
        if isinstance(context, dict):
            task_prompt = context.get('task', '')
            # Add context about recent messages and other agents for collaborative awareness
            recent_msgs = context.get('recent_messages', [])
            if recent_msgs:
                task_prompt += "\n\nRecent team messages:\n"
                for msg in recent_msgs[-3:]:  # Last 3 messages
                    task_prompt += f"- {msg['sender']}: {msg['content'][:200]}\n"
        elif hasattr(context, 'get_user_input'):
            task_prompt = context.get_user_input()
        elif hasattr(context, 'task'):
            task_prompt = context.task
        elif isinstance(context, str):
            task_prompt = context
        else:
            task_prompt = str(context)
        
        # Add rate limiting delay to avoid hitting API limits
        await asyncio.sleep(Config.RATE_LIMIT_DELAY)
        
        # Get a fresh client with rotated API key
        client = get_client()
        
        # Anthropic requires system prompt in a separate parameter
        message = client.messages.create(
            model=Config.MODEL,
            max_tokens=Config.MAX_TOKENS,
            temperature=temperature,
            system=system_prompt,
            messages=[
                {"role": "user", "content": task_prompt}
            ]
        )
        return message.content[0].text
    
    return llm_agent

