"""
{{ tool_name|capitalize }} tool for EvenAge agents.

{{ tool_description }}
"""

from __future__ import annotations
import json
from typing import Any

try:
    from pydantic import BaseModel, Field
except Exception:
    BaseModel = object  # type: ignore
    def Field(*a, **k):  # type: ignore
        return None

from evenage.core import tool as tool_decorator


class InputModel(BaseModel):  # type: ignore[misc]
{% if params and params|length > 0 %}
{%   for param in params %}
    {{ param.name }}: Any = Field(description="{{ param.description|default('Input parameter') }}")
{%   endfor %}
{% else %}
    # Define inputs for this tool if needed
    query: Any = Field(description="Primary input for the tool")
{% endif %}


@tool_decorator(
    name="{{ tool_name }}",
    description="{{ tool_description }}"
)
def {{ tool_function_name }}(*args, **kwargs) -> str:
    """
    {{ tool_description }}
    Automatically adapts to any LLM-generated param keys.
    """
    # --- Extract primary input robustly ---
    candidates: list[Any] = []
{% if params and params|length > 0 %}
{%   for param in params %}
    candidates.append(kwargs.get("{{ param.name }}"))
{%   endfor %}
{% endif %}
    candidates.extend([
        kwargs.get("query"),
        kwargs.get("text"),
        kwargs.get("message"),
        kwargs.get("task"),
        kwargs.get("data"),
        kwargs.get("document"),
        (args[0] if args else None),
    ])

    primary = next((c for c in candidates if c not in (None, "")), "")
    if primary == "":
        return "Error: Missing required input."

    try:
        # TODO: Implement tool logic using `primary` and any extra `kwargs`.
        # Convert complex inputs (dict/list) to string when needed:
        if isinstance(primary, (dict, list)):
            primary_str = json.dumps(primary, ensure_ascii=False)
        else:
            primary_str = str(primary)

        # Example placeholder behavior (replace with real implementation):
        return f"{{ tool_name }} executed. Input length: {len(primary_str)}"

    except Exception as e:
        return f"Error: {str(e)}"
