"""Agent Inventory Tool for querying active agents and user-accessible agents."""

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

import aiohttp


@dataclass
class AgentInfo:
    """Agent information from the AI Inventory service."""

    id: str
    name: str
    representation_name: str
    about: str
    status: str
    life_status: str
    document: str = ""
    example_prompts: List[str] = field(default_factory=list)
    categories: List[Dict[str, str]] = field(default_factory=list)
    tags: List[Dict[str, str]] = field(default_factory=list)

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "AgentInfo":
        return cls(
            id=str(data.get("id", "")),
            name=data.get("name", ""),
            representation_name=data.get("representationName", ""),
            about=data.get("about", ""),
            status=data.get("status", ""),
            life_status=data.get("lifeStatus", ""),
            document=data.get("document", ""),
            example_prompts=data.get("examplePrompts") or [],
            categories=[
                {"id": str(c.get("id", "")), "name": c.get("name", "")}
                for c in data.get("categories", [])
            ],
            tags=[
                {"id": str(t.get("id", "")), "name": t.get("name", "")}
                for t in data.get("tags", [])
            ],
        )


class AgentInventoryTool:
    """
    Tool for querying the AI Inventory service.

    Usage:
        inv = agent.tools.agent_inventory

        # Get all active agents
        agents = await inv.get_active_agents()

        # Get agents accessible to a specific user
        user_agents = await inv.get_user_agents(user_id="...")
    """

    def __init__(self, base_url: str):
        self.base_url = base_url.rstrip("/")
        self._session: Optional[aiohttp.ClientSession] = None

    @classmethod
    def from_gateway(cls, gateway_client) -> "AgentInventoryTool":
        """Create from GatewayClient instance."""
        return cls(gateway_client.ai_inventory_url)

    async def _get_session(self) -> aiohttp.ClientSession:
        if self._session is None or self._session.closed:
            timeout = aiohttp.ClientTimeout(total=30.0)
            self._session = aiohttp.ClientSession(timeout=timeout)
        return self._session

    async def close(self):
        """Close the HTTP session."""
        if self._session and not self._session.closed:
            await self._session.close()

    async def _get(self, path: str, params: Optional[Dict] = None) -> Any:
        session = await self._get_session()
        url = f"{self.base_url}{path}"
        async with session.get(url, params=params) as response:
            response.raise_for_status()
            return await response.json()

    async def get_active_agents(self) -> List[AgentInfo]:
        """Get all agents with status=active and lifeStatus=active."""
        data = await self._get(
            "/api/v1/agents",
            params={"status": "active", "lifeStatus": "active"},
        )
        return [AgentInfo.from_dict(a) for a in data]

    async def get_user_agents(self, user_id: str) -> List[AgentInfo]:
        """
        Get active agents accessible to a specific user.

        Filters by role-based access and direct user permissions.

        Args:
            user_id: The user's UUID.
        """
        data = await self._get(
            "/api/v1/agents",
            params={
                "status": "active",
                "lifeStatus": "active",
                "userId": user_id,
            },
        )
        return [AgentInfo.from_dict(a) for a in data]
