"""Directory tools — find agents, verify identity, get own profile."""

from __future__ import annotations

import json

from mcp.server.fastmcp import FastMCP

from amrood_mcp.api_client import AmroodAPI
from amrood_mcp.auth import AuthState


def register_directory_tools(mcp: FastMCP, api: AmroodAPI, auth: AuthState):
    """Register directory and identity tools on the MCP server."""

    @mcp.tool()
    async def amrood_find_agent(
        search: str | None = None,
        min_trust_score: int | None = None,
        limit: int = 10,
    ) -> str:
        """Search the Amrood agent directory.

        Find agents on the network by name. Returns agent IDs, names,
        trust scores, and transaction counts. Use this to discover agents
        you want to pay or interact with.

        Args:
            search: Search term to filter agents by name
            min_trust_score: Minimum trust score (0-100) to filter by
            limit: Number of results to return (default 10)
        """
        params: dict = {"limit": min(limit, 50)}
        if search:
            params["search"] = search
        if min_trust_score is not None:
            params["min_trust_score"] = min_trust_score

        data = await api.get("/v1/directory", params=params)
        return json.dumps(data, indent=2)

    @mcp.tool()
    async def amrood_verify_agent(agent_id: str) -> str:
        """Verify an agent's identity and get their signed trust profile.

        Returns a cryptographically signed verification payload containing
        the agent's trust score, KYC status, and network membership details.
        Use this before paying an agent to confirm they are legitimate.

        Args:
            agent_id: The agent ID to verify (e.g. "agt_abc123")
        """
        try:
            data = await api.get(f"/v1/directory/{agent_id}/verify")
            return json.dumps(data, indent=2)
        except Exception as e:
            return f"Verification failed: {e}"

    @mcp.tool()
    async def amrood_identity() -> str:
        """Get this agent's own public profile and trust score.

        Returns the agent's name, trust score, verification status,
        network age, and transaction count as seen by other agents.
        """
        agent_id = auth.agent_id
        if not agent_id and auth.has_agent_key:
            try:
                me = await api.get("/v1/agents/me")
                agent_id = me.get("agent_id")
                auth.agent_id = agent_id
            except Exception:
                pass
        if not agent_id:
            return "Error: No agent configured. Set AMROOD_AGENT_KEY or complete onboarding first."

        try:
            data = await api.get(f"/v1/directory/{agent_id}")
            return json.dumps(data, indent=2)
        except Exception as e:
            return f"Could not fetch identity: {e}"
