"""Use these tools in a CrewAI Agent; no mail-payment operations are exposed."""

import asyncio
import json
from typing import Any, Type
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
from postalform_client import call_tool, list_tools


class EmptyInput(BaseModel):
    pass


class PostalFormInput(BaseModel):
    name: str = Field(description="Exact tool name from PostalFormTools, including postalform.")
    arguments: dict[str, Any] = Field(description="Arguments matching that live input schema")


class PostalFormTools(BaseTool):
    name: str = "postalform_tools"
    description: str = "Fetch live PostalForm discovery, unpaid draft and status tool schemas."
    args_schema: Type[BaseModel] = EmptyInput

    async def _arun(self) -> str:
        return json.dumps(await list_tools())

    def _run(self) -> str:
        return asyncio.run(self._arun())


class PostalFormCall(BaseTool):
    name: str = "postalform_call"
    description: str = (
        "Call an allowed PostalForm tool using its live schema. "
        "Present draft preview and checkout URL to the owner; this tool cannot pay."
    )
    args_schema: Type[BaseModel] = PostalFormInput

    async def _arun(self, name: str, arguments: dict[str, Any]) -> str:
        return json.dumps(await call_tool(name, arguments))

    def _run(self, name: str, arguments: dict[str, Any]) -> str:
        return asyncio.run(self._arun(name, arguments))
