"""
Semantic Kernel adapter for UASS integration.
"""

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


class SemanticKernelAdapter(FrameworkAdapter):
    """
    Adapter for integrating Semantic Kernel with UASS.
    
    Usage:
        from uass import UASSClient, RedisBackend, SemanticKernelAdapter
        
        client = UASSClient(backend=RedisBackend())
        adapter = SemanticKernelAdapter(client)
        
        # Sync Semantic Kernel agent state
        adapter.sync_to_uass("session_123", "agent_1", kernel, agent, chat_history)
        
        # 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,
        kernel: Any = None,
        agent: Any = None,
        chat_history: Optional[list] = None,
        variables: Optional[Dict[str, Any]] = None,
    ) -> bool:
        """
        Sync Semantic Kernel state to UASS.
        
        Args:
            session_id: Session identifier
            agent_id: Agent identifier
            kernel: Semantic Kernel kernel instance (optional)
            agent: Semantic Kernel agent instance (optional)
            chat_history: Chat history/messages (optional)
            variables: Additional variables (optional)
            
        Returns:
            True if successful, False otherwise
        """
        uass_variables = variables or {}
        context = {}
        uass_messages = []
        actions = []
        
        if kernel:
            # Extract kernel configuration
            if hasattr(kernel, "services"):
                context["kernel_services"] = str(type(kernel.services).__name__)
            if hasattr(kernel, "plugins"):
                context["kernel_plugins"] = str(len(getattr(kernel.plugins, "plugins", {})))
        
        if agent:
            # Extract agent information
            uass_variables["agent_name"] = getattr(agent, "name", agent_id)
            if hasattr(agent, "description"):
                uass_variables["agent_description"] = getattr(agent, "description", "")
            if hasattr(agent, "instructions"):
                uass_variables["agent_instructions"] = getattr(agent, "instructions", "")
        
        if chat_history:
            # Convert Semantic Kernel messages to UASS format
            for msg in chat_history:
                if isinstance(msg, dict):
                    uass_messages.append(msg)
                else:
                    # Handle Semantic Kernel message objects
                    uass_messages.append({
                        "role": getattr(msg, "role", getattr(msg, "author_role", "unknown")),
                        "content": getattr(msg, "content", getattr(msg, "text", str(msg))),
                        "timestamp": getattr(msg, "timestamp", None),
                    })
        
        framework_state = {}
        if kernel:
            framework_state["kernel_type"] = type(kernel).__name__
        if agent:
            framework_state["agent_type"] = type(agent).__name__
        
        return self.client.write_state(
            session_id=session_id,
            agent_id=agent_id,
            framework="semantic_kernel",
            variables=uass_variables,
            context=context,
            messages=uass_messages,
            actions=actions,
            framework_state=framework_state,
        )
    
    def sync_from_uass(
        self,
        session_id: str,
        agent_id: str,
    ) -> Optional[Dict[str, Any]]:
        """
        Sync state from UASS to Semantic Kernel format.
        
        Args:
            session_id: Session identifier
            agent_id: Agent identifier
            
        Returns:
            Dictionary with Semantic Kernel-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 Semantic Kernel-compatible format
        return {
            "messages": unified_state.state.messages,
            "variables": unified_state.state.variables,
            "context": unified_state.state.context,
            "actions": unified_state.state.actions,
            "framework_state": unified_state.state.framework_state,
        }

