"""Built-in tool: list available agent profiles with structured descriptions."""

from navi.tools._internal.base import Tool, ToolContext, ToolResult


class ListProfilesTool(Tool):
    name = "list_profiles"
    description = (
        "List all available agent profiles with their specialization, use cases, and key tools. "
        "Call this before switch_profile when you need details about what a profile does "
        "or to confirm which profile best fits the current task."
    )
    parameters = {
        "type": "object",
        "properties": {
            "profile_id": {
                "type": "string",
                "description": "Optional. Return full details for one specific profile only.",
            }
        },
        "required": [],
    }

    def __init__(self, profile_registry) -> None:
        self._profiles = profile_registry

    async def execute(self, params: dict, ctx: ToolContext | None = None) -> ToolResult:
        profile_id = (params.get("profile_id") or "").strip()

        if profile_id:
            try:
                p = self._profiles.get(profile_id)
            except Exception:
                available = ", ".join(x.id for x in self._profiles.all())
                return ToolResult(
                    success=False, output="",
                    error=f"Profile '{profile_id}' not found. Available: {available}",
                )
            return ToolResult(success=True, output=self._format(p))

        sections = [self._format(p) for p in self._profiles.all()]
        return ToolResult(success=True, output="\n\n".join(sections))

    @staticmethod
    def _format(p) -> str:
        fd = p.full_description or {}
        tag = " [subagent only]" if getattr(p, "is_subagent_only", False) else ""
        lines = [f"## {p.name}  [{p.id}]{tag}"]
        if p.short_description:
            lines.append(p.short_description)
        if fd.get("specialization"):
            lines.append(f"\nSpecialization: {fd['specialization']}")
        if fd.get("when_to_use"):
            lines.append(f"When to use:    {fd['when_to_use']}")
        if fd.get("key_tools"):
            tools = fd["key_tools"]
            if isinstance(tools, list):
                tools = ", ".join(tools)
            lines.append(f"Key tools:      {tools}")
        return "\n".join(lines)
