"""Amrood MCP Server entry point.

Registers all tools. The agent tools will check auth state at call time
and return helpful errors if not yet authenticated.
"""

from __future__ import annotations

import logging

from mcp.server.fastmcp import FastMCP

from amrood_mcp.api_client import AmroodAPI
from amrood_mcp.auth import AuthState
from amrood_mcp.tools.agent import register_agent_tools
from amrood_mcp.tools.directory import register_directory_tools
from amrood_mcp.tools.onboarding import register_onboarding_tools

logger = logging.getLogger("amrood-mcp")

mcp = FastMCP(
    "amrood",
    instructions="Amrood — payment infrastructure for AI agents. "
                 "Create agents, fund wallets, pay other agents on the network.",
)

auth = AuthState()
api = AmroodAPI(auth)


async def _resolve_agent_id():
    """Call GET /v1/agents/me to resolve agent_id from the agent key."""
    if auth.has_agent_key and not auth.agent_id:
        try:
            data = await api.get("/v1/agents/me")
            auth.agent_id = data.get("agent_id")
            logger.info("Resolved agent_id: %s", auth.agent_id)
        except Exception as e:
            logger.warning("Could not resolve agent_id from key: %s", e)


@mcp.tool()
async def amrood_status() -> str:
    """Check current Amrood authentication status.

    Shows whether an agent key is configured, the agent ID,
    and whether session auth is active. Useful for debugging
    connection issues.
    """
    if auth.has_agent_key and not auth.agent_id:
        await _resolve_agent_id()

    import json
    info = {
        "has_agent_key": auth.has_agent_key,
        "agent_id": auth.agent_id,
        "has_session": auth.has_session,
        "base_url": api._base,
    }
    if not auth.is_authenticated:
        info["hint"] = "Set AMROOD_AGENT_KEY env var, or use amrood_register to start onboarding."
    return json.dumps(info, indent=2)


register_agent_tools(mcp, api, auth)
register_directory_tools(mcp, api, auth)
register_onboarding_tools(mcp, api, auth)


def main():
    mcp.run()


if __name__ == "__main__":
    main()
