"""PostalForm hosted-checkout MCP adapter. No payment tools are exposed."""

from typing import Any

MCP_URL = "https://postalform.com/mcp"
ALLOWED_TOOLS = frozenset({
    "postalform.list_forms",
    "postalform.get_form_schema",
    "postalform.search_addresses",
    "postalform.create_letter_order_draft",
    "postalform.create_order_draft",
    "postalform.create_form_order_draft",
    "postalform.get_order_status",
})


async def list_tools() -> list[dict[str, Any]]:
    """Fetch live input schemas for the supported discovery and unpaid draft tools."""
    from mcp import ClientSession
    from mcp.client.streamable_http import streamablehttp_client

    async with streamablehttp_client(MCP_URL) as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            result = []
            cursor = None
            while True:
                page = await session.list_tools(cursor=cursor)
                result.extend(
                    tool.model_dump(mode="json", exclude_none=True)
                    for tool in page.tools if tool.name in ALLOWED_TOOLS
                )
                cursor = page.nextCursor
                if not cursor:
                    return result


async def call_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
    """Call a permitted tool once; retain isError, structuredContent and text results."""
    if name not in ALLOWED_TOOLS:
        raise ValueError("This integration supports discovery and unpaid drafts, not payment.")
    from mcp import ClientSession
    from mcp.client.streamable_http import streamablehttp_client

    # Do not retry mutations automatically: a timeout does not prove a draft was not created.
    async with streamablehttp_client(MCP_URL) as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            result = await session.call_tool(name, arguments)
            return result.model_dump(mode="json", exclude_none=True)
