#!/usr/bin/env python3
"""
Agent Registry for Swarm AI System

This file contains the agent registry system that manages swarm agents,
model adapters, and provides utilities for agent creation and management.
"""

import time
import json
from typing import Dict, List, Any, Optional, Union
from .swarm_agent_base import SwarmAgent
from .model_adapters import (
    VanillaAIAdapter,
    CommunityPatchAIAdapter,
    RICEAIAdapter,
    QyvarianAIAdapter,
    DefaultAIAdapter
)
class AgentRegistry:
    """
    Registry for swarm agents and model adapters.
    
    This class manages:
    - Agent registration and lifecycle
    - Model adapter management
    - Agent template definitions
    - Agent creation and configuration
    """
    
    def __init__(self):
        self.agents = {}
        self.model_templates = {}
        self.agent_templates = {}
        self.model_adapters = {}
        
    def register_model_template(self, name: str, config: Dict[str, Any]):
        """
        Register a reusable model configuration.
        
        Args:
            name: Name of the model template
            config: Model configuration
        """
        self.model_templates[name] = config
        
    def register_agent_template(self, name: str, config: Dict[str, Any]):
        """
        Register a reusable agent template.
n        Args:
            name: Name of the agent template
            config: Agent configuration
        """
        self.agent_templates[name] = config
        
    def create_agent(self, agent_config: Dict[str, Any]) -> SwarmAgent:
        """
        Create a swarm agent with the specified configuration.
n        Args:
            agent_config: Agent configuration
            
        Returns:
            Created agent instance
        """
        agent_id = f"{agent_config['type']}_{len(self.agents)}"
        
        # Determine appropriate model
        model_config = self.get_model_for_agent_type(agent_config["type"])
        
        # Create agent
        agent = SwarmAgent(
            agent_id=agent_id,
            agent_type=agent_config["type"],
            priority=agent_config["priority"]
        )
        
        # Assign model adapter
        agent.set_model_adapter(self.create_model_adapter(
            model_config["type"], model_config["params"]
        ))
        
        self.agents[agent_id] = agent
        return agent
        
    def get_model_for_agent_type(self, agent_type: str) -> Dict[str, Any]:
        """
        Get appropriate model configuration for agent type.
n        Args:
            agent_type: Type of agent
            
        Returns:
            Model configuration
        """
        # Define model preferences for agent types
        model_preferences = {
            "strategy": {"type": "organic", "params": {"depth": "calculating"}},
            "economy": {"type": "cp", "params": {"focus": "specialization"}},
            "military": {"type": "vanilla", "params": {"focus": "tactics"}},
            "social": {"type": "rice", "params": {"focus": "cooperation"}},
            "religion": {"type": "organic", "params": {"focus": "strategy"}},
            "intrigue": {"type": "organic", "params": {"depth": "calculating"}},
            "succession": {"type": "organic", "params": {"focus": "optimization"}},
            "military_tactics": {"type": "vanilla", "params": {"focus": "counter_ma"}},
            "dread": {"type": "organic", "params": {"focus": "management"}},
            "economy": {"type": "cp", "params": {"focus": "specialization"}},
            "memory": {"type": "organic", "params": {"focus": "modeling"}},
            "religion": {"type": "rice", "params": {"focus": "strategy"}},
            "government": {"type": "organic", "params": {"focus": "specialization"}},
            "artifact": {"type": "organic", "params": {"focus": "management"}},
            "crusade": {"type": "organic", "params": {"focus": "coordination"}}
        }
        
        return model_preferences.get(agent_type, {"type": "organic", "params": {}})
        
    def register_model_adapter(self, model_id: str, model_adapter):
        """
        Register a model adapter.
n        Args:
            model_id: Model identifier
            model_adapter: Model adapter instance
        """
        self.model_adapters[model_id] = model_adapter
        
    def get_model_adapter(self, model_id: str):
        """
        Get model adapter by ID.
n        Args:
            model_id: Model identifier
            
        Returns:
            Model adapter instance
        """
        return self.model_adapters.get(model_id)
        
    def create_model_adapter(self, model_type: str, model_params: Dict[str, Any]):
        """
        Create model adapter for the specified type.
n        Args:
            model_type: Type of model adapter
            model_params: Model parameters
            
        Returns:
            Model adapter instance
        """
        if model_type == "vanilla":
            return VanillaAIAdapter(model_params)
        elif model_type == "cp":
            return CommunityPatchAIAdapter(model_params)
        elif model_type == "rice":
            return RICEAIAdapter(model_params)
        elif model_type == "organic":
            return QyvarianAIAdapter(model_params)
        else:
            return DefaultAIAdapter(model_params)
            
    def get_agent_count(self) -> int:
        """
        Get the number of registered agents.
n        Returns:
            Number of agents
        """
        return len(self.agents)
        
    def get_agents_by_type(self, agent_type: str) -> List[SwarmAgent]:
        """
        Get all agents of a specific type.
n        Args:
            agent_type: Type of agent
            
        Returns:
            List of agents
        """
        return [agent for agent in self.agents.values() if agent.agent_type == agent_type]
        
    def remove_agent(self, agent_id: str) -> bool:
        """
        Remove an agent.
n        Args:
            agent_id: Agent identifier
            
        Returns:
            True if agent was removed, False otherwise
        """
        if agent_id in self.agents:
            del self.agents[agent_id]
            return True
        return False
        
    def get_agent_status(self, agent_id: str) -> Dict[str, Any]:
        """
        Get status information for an agent.
n        Args:
            agent_id: Agent identifier
            
        Returns:
            Agent status information
        """
        if agent_id in self.agents:
            return self.agents[agent_id].get_status()
        return {}
        
    def export_agent_configs(self) -> List[Dict[str, Any]]:
        """
        Export agent configurations.
n        Returns:
            List of agent configurations
        """
        return [
            {
                "id": agent.agent_id,
                "type": agent.agent_type,
                "priority": agent.priority
            }
            for agent in self.agents.values()
        ]