"""Application for interacting with {{ base_name }} via MCP."""
from typing import Any
from fastmcp import Client
{% if auth_type == "bearer" %}
from mcp_skill.auth import BearerAuth
{% elif auth_type == "header" %}
from mcp_skill.auth import ApiKeyAuth
{% elif auth_type == "oauth" %}
from mcp_skill.auth import OAuth
{% endif %}
import json
{% if auth_type == "none" %}
import warnings
{% endif %}

class {{ class_name }}:
    """
    Application for interacting with {{ base_name }} via MCP.
    Provides tools to {{ brief }}.
    """

{% if auth_type in ("bearer", "header") %}
    def __init__(self, url: str = "{{ server_url }}", auth=None) -> None:
        self.url = url
{% if auth_type == "bearer" %}
        self._auth = BearerAuth(api_key=auth, server_url=url)
{% else %}
        self._auth = ApiKeyAuth(api_key=auth, server_url=url, header_name="{{ auth_header }}")
{% endif %}
{% elif auth_type == "oauth" %}
    def __init__(self, url: str = "{{ server_url }}", auth=None) -> None:
        self.url = url
        self._oauth_auth = auth
{% else %}
    def __init__(self, url: str = "{{ server_url }}", auth=None) -> None:
        self.url = url
        if auth is not None:
            warnings.warn(
                "This server requires no authentication; the 'auth' argument will be ignored.",
                UserWarning,
                stacklevel=2,
            )
{% endif %}

{% if auth_type in ("bearer", "header") %}
    def _get_client(self) -> Client:
        return Client(self.url, auth=self._auth)
{% elif auth_type == "oauth" %}
    def _get_client(self) -> Client:
        oauth = self._oauth_auth or OAuth()
        return Client(self.url, auth=oauth)
{% else %}
    def _get_client(self) -> Client:
        return Client(self.url)
{% endif %}

{% for method in methods %}
    async def {{ method.name }}({{ method.signature }}) -> dict[str, Any]:
        """
        {{ method.description }}

{% if method.params %}
        Args:
{% for p in method.params %}
            {{ p.name }}: {{ p.doc }}
{% endfor %}

{% endif %}
        Returns:
            Tool execution result

        Tags:
            {{ method.tags }}
        """
        async with self._get_client() as client:
            call_args = {}
{% for p in method.params %}
{% if p.required %}
            call_args["{{ p.name }}"] = {{ p.name }}
{% else %}
            if {{ p.name }} is not None:
                call_args["{{ p.name }}"] = {{ p.name }}
{% endif %}
{% endfor %}
            result = await client.call_tool("{{ method.tool_name }}", call_args)
            texts = []
            for block in result.content:
                if hasattr(block, "text"):
                    texts.append(block.text)
            text = "\n".join(texts)
            try:
                return json.loads(text)
            except (json.JSONDecodeError, TypeError):
                return {"result": text}

{% endfor %}
    def list_tools(self):
        return [{{ method_refs }}]
