"""
AgentsIndex.ai Python Client

Browse AI agents, frameworks, and tools programmatically.
Directory: https://agentsindex.ai
"""

__version__ = "0.1.0"

import json
from urllib.request import urlopen, Request


BASE_URL = "https://agentsindex.ai"


class AgentsIndex:
    """Client for browsing AgentsIndex.ai programmatically.

    Args:
        base_url: Base URL override (default: https://agentsindex.ai)
    """

    def __init__(self, base_url=None):
        self.base_url = base_url or BASE_URL

    def _fetch(self, path):
        req = Request(
            f"{self.base_url}{path}",
            headers={"Accept": "application/json"},
        )
        with urlopen(req) as resp:
            return json.loads(resp.read())

    @property
    def url(self):
        """Get the directory URL."""
        return self.base_url

    def get_tool(self, slug):
        """Get a tool by slug.

        Args:
            slug: Tool slug (e.g. 'crewai')

        Returns:
            dict: Tool data
        """
        return self._fetch(f"/api/tools/{slug}")

    def list_tools(self, **params):
        """List tools with optional filters.

        Returns:
            list: List of tools
        """
        query = "&".join(f"{k}={v}" for k, v in params.items())
        path = f"/api/tools?{query}" if query else "/api/tools"
        return self._fetch(path)

    def list_categories(self):
        """List all categories.

        Returns:
            list: List of categories
        """
        return self._fetch("/api/categories")

    def info(self):
        """Get directory info.

        Returns:
            dict: Directory metadata
        """
        return {
            "name": "AgentsIndex.ai",
            "url": self.base_url,
            "description": "The AI agent ecosystem, indexed.",
            "github": "https://github.com/AgentsIndex",
            "twitter": "https://x.com/AgentsIndex",
        }
