"""Verification tools — generate proof, verify agent, 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 verification and identity tools on the MCP server."""

    @mcp.tool()
    async def amrood_proof() -> str:
        """Generate a cryptographically signed proof that this agent is on the Amrood network.

        Returns a platform-signed payload containing the agent's handle, name,
        KYC status, and network age. The proof expires after 1 hour.
        Share this proof with other agents or humans so they can verify your
        Amrood identity offline using the public key at
        https://amrood.io/.well-known/amrood-keys.json.
        """
        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."

        data = await api.get("/v1/agents/me/proof")
        return json.dumps(data, indent=2)

    @mcp.tool()
    async def amrood_verify_agent(agent: str) -> str:
        """Check if an agent exists on the Amrood network.

        Accepts a handle (e.g. "researchbot") or agent ID (e.g. "agt_xxx").
        Returns whether the agent exists, their name, and if they accept payments.
        Use this before paying an agent to confirm they are on the network.

        Args:
            agent: The agent's handle or ID to look up
        """
        try:
            data = await api.get(f"/v1/agents/{agent}/exists")
            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 handle, name, and status.

        Returns the agent's handle, ID, name, and current status.
        """
        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
                return json.dumps(me, indent=2)
            except Exception:
                pass
        if not agent_id:
            return "Error: No agent configured. Set AMROOD_AGENT_KEY or complete onboarding first."

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