"""
Agent Template Base Classes

Defines the structure for agent templates and their metadata.
"""

from dataclasses import dataclass, field
from typing import List, Optional, Dict, Any
from enum import Enum

from ...intelligence.domain_analyzer import TaskDomain


class CollaborationStyle(Enum):
    """How an agent prefers to work with others."""
    INDEPENDENT = "independent"      # Works alone, reports results
    COLLABORATIVE = "collaborative"  # Works alongside other agents
    SUPERVISORY = "supervisory"      # Oversees and coordinates others
    SUPPORTIVE = "supportive"        # Assists other agents as needed


class AgentRole(Enum):
    """Role an agent can play in a project team."""
    LEAD = "lead"              # Primary agent for the task
    SPECIALIST = "specialist"  # Domain expert for specific work
    REVIEWER = "reviewer"      # Reviews and provides feedback
    SUPPORT = "support"        # Assists other agents


@dataclass
class AgentCapability:
    """A specific capability an agent has."""
    name: str
    description: str
    proficiency: float = 1.0  # 0.0 to 1.0


@dataclass
class AgentTemplate:
    """
    Template for creating specialized agents.

    Templates define the characteristics, capabilities, and behavior
    of agent types that can be instantiated for specific projects.
    """

    # Identity
    id: str
    name: str
    description: str

    # Domain classification
    domain: TaskDomain
    secondary_domains: List[TaskDomain] = field(default_factory=list)

    # Capabilities
    capabilities: List[AgentCapability] = field(default_factory=list)
    suggested_tools: List[str] = field(default_factory=list)

    # Behavior
    collaboration_style: CollaborationStyle = CollaborationStyle.COLLABORATIVE
    default_role: AgentRole = AgentRole.SPECIALIST

    # Prompts
    system_prompt: str = ""
    task_prompt_template: str = ""

    # Metadata
    version: str = "1.0.0"
    author: str = "system"
    tags: List[str] = field(default_factory=list)

    # Configuration
    config: Dict[str, Any] = field(default_factory=dict)

    def matches_domain(self, domain: TaskDomain) -> bool:
        """Check if this template is suitable for a domain."""
        return domain == self.domain or domain in self.secondary_domains

    def get_capability_names(self) -> List[str]:
        """Get list of capability names."""
        return [c.name for c in self.capabilities]

    def to_dict(self) -> Dict[str, Any]:
        """Convert template to dictionary for serialization."""
        return {
            "id": self.id,
            "name": self.name,
            "description": self.description,
            "domain": self.domain.value,
            "secondary_domains": [d.value for d in self.secondary_domains],
            "capabilities": [
                {"name": c.name, "description": c.description, "proficiency": c.proficiency}
                for c in self.capabilities
            ],
            "suggested_tools": self.suggested_tools,
            "collaboration_style": self.collaboration_style.value,
            "default_role": self.default_role.value,
            "system_prompt": self.system_prompt,
            "task_prompt_template": self.task_prompt_template,
            "version": self.version,
            "author": self.author,
            "tags": self.tags,
            "config": self.config,
        }

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AgentTemplate":
        """Create template from dictionary."""
        return cls(
            id=data["id"],
            name=data["name"],
            description=data["description"],
            domain=TaskDomain(data["domain"]),
            secondary_domains=[TaskDomain(d) for d in data.get("secondary_domains", [])],
            capabilities=[
                AgentCapability(
                    name=c["name"],
                    description=c["description"],
                    proficiency=c.get("proficiency", 1.0)
                )
                for c in data.get("capabilities", [])
            ],
            suggested_tools=data.get("suggested_tools", []),
            collaboration_style=CollaborationStyle(
                data.get("collaboration_style", "collaborative")
            ),
            default_role=AgentRole(data.get("default_role", "specialist")),
            system_prompt=data.get("system_prompt", ""),
            task_prompt_template=data.get("task_prompt_template", ""),
            version=data.get("version", "1.0.0"),
            author=data.get("author", "system"),
            tags=data.get("tags", []),
            config=data.get("config", {}),
        )


@dataclass
class AgentTeamComposition:
    """
    Recommended team composition for a task.

    Describes which agent templates should be used and their roles.
    """

    lead: AgentTemplate
    specialists: List[AgentTemplate] = field(default_factory=list)
    reviewers: List[AgentTemplate] = field(default_factory=list)
    support: List[AgentTemplate] = field(default_factory=list)

    @property
    def all_agents(self) -> List[AgentTemplate]:
        """Get all agents in the team."""
        return [self.lead] + self.specialists + self.reviewers + self.support

    @property
    def team_size(self) -> int:
        """Get total team size."""
        return len(self.all_agents)
