"""
AutoGen adapter for UASS integration.
"""

from typing import Optional, Dict, Any, List
from ..client import UASSClient
from ..adapters.base import FrameworkAdapter


class AutoGenAdapter(FrameworkAdapter):
    """
    Adapter for integrating AutoGen with UASS.
    
    Usage:
        from uass import UASSClient, RedisBackend, AutoGenAdapter
        
        client = UASSClient(backend=RedisBackend())
        adapter = AutoGenAdapter(client)
        
        # Sync AutoGen conversation state
        adapter.sync_to_uass("session_123", "agent_1", agent, messages)
        
        # Read state from another framework
        state = adapter.sync_from_uass("session_123", "agent_1")
    """
    
    def sync_to_uass(
        self,
        session_id: str,
        agent_id: str,
        agent: Any = None,
        messages: Optional[List[Any]] = None,
    ) -> bool:
        """
        Sync AutoGen state to UASS.
        
        Args:
            session_id: Session identifier
            agent_id: Agent identifier
            agent: AutoGen agent instance (optional)
            messages: AutoGen conversation messages (optional)
            
        Returns:
            True if successful, False otherwise
        """
        # Extract state from AutoGen
        variables = {}
        context = {}
        uass_messages = []
        
        if agent:
            # Extract agent configuration
            variables["name"] = getattr(agent, "name", agent_id)
            variables["system_message"] = getattr(agent, "system_message", "")
            if hasattr(agent, "llm_config"):
                context["llm_config"] = str(getattr(agent, "llm_config", {}))
        
        if messages:
            # Convert AutoGen messages to UASS format
            for msg in messages:
                if isinstance(msg, dict):
                    uass_messages.append(msg)
                else:
                    # Handle AutoGen message objects
                    uass_messages.append({
                        "role": getattr(msg, "role", "unknown"),
                        "name": getattr(msg, "name", ""),
                        "content": getattr(msg, "content", str(msg)),
                    })
        
        framework_state = {}
        if agent:
            framework_state["agent_type"] = type(agent).__name__
            framework_state["agent_config"] = str(vars(agent))
        
        return self.client.write_state(
            session_id=session_id,
            agent_id=agent_id,
            framework="autogen",
            variables=variables,
            context=context,
            messages=uass_messages,
            framework_state=framework_state,
        )
    
    def sync_from_uass(
        self,
        session_id: str,
        agent_id: str,
    ) -> Optional[Dict[str, Any]]:
        """
        Sync state from UASS to AutoGen format.
        
        Args:
            session_id: Session identifier
            agent_id: Agent identifier
            
        Returns:
            Dictionary with AutoGen-compatible state, or None if not found
        """
        unified_state = self.client.read_full_state(session_id, agent_id)
        if unified_state is None:
            return None
        
        # Return AutoGen-compatible format
        return {
            "messages": unified_state.state.messages,
            "variables": unified_state.state.variables,
            "context": unified_state.state.context,
            "framework_state": unified_state.state.framework_state,
        }

