from typing import Dict, List, Optional
from .card import AgentCard


class Registry:
    """
    Feature 5: Agent Registry & Discovery
    Feature 7: Agent discovery by skill
    """

    def __init__(self):
        self._agents: Dict[str, dict] = {}

    def register(self, agent, endpoint: str = None):
        """Register an agent in the registry."""
        card = agent.card()
        if endpoint:
            card.endpoint = endpoint
        self._agents[agent.name] = {
            "card": card,
            "agent": agent,
        }
        return card

    def unregister(self, name: str):
        """Remove agent from registry."""
        if name in self._agents:
            del self._agents[name]

    def discover(self, skill: str = None, tool: str = None, provider: str = None) -> List[AgentCard]:
        """Find agents by skill, tool, or provider."""
        results = []
        for entry in self._agents.values():
            card = entry["card"]
            if skill and skill not in card.skills:
                continue
            if tool and tool not in card.tools:
                continue
            if provider and card.provider != provider:
                continue
            results.append(card)
        return results

    def get(self, name: str):
        """Get agent by name."""
        entry = self._agents.get(name)
        return entry["agent"] if entry else None

    def get_card(self, name: str) -> Optional[AgentCard]:
        entry = self._agents.get(name)
        return entry["card"] if entry else None

    def list_all(self) -> List[AgentCard]:
        return [e["card"] for e in self._agents.values()]

    def health_check(self) -> dict:
        results = {}
        for name, entry in self._agents.items():
            results[name] = entry["agent"].health()
        return results

    def __len__(self):
        return len(self._agents)

    def __repr__(self):
        return f"Registry(agents={list(self._agents.keys())})"
