"""Web-UI tool renderer registry."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Callable


@dataclass
class ToolRenderResult:
    """Result from rendering a tool call."""

    content: str  # HTML/template content
    is_custom: bool = False


# Type for renderer function: (params, result, is_streaming) -> ToolRenderResult
ToolRenderer = Callable[[Any, Any, bool], ToolRenderResult]

_tool_renderers: dict[str, ToolRenderer] = {}


def register_tool_renderer(tool_name: str, renderer: ToolRenderer) -> None:
    """Register a custom renderer for a tool."""
    _tool_renderers[tool_name] = renderer


def get_tool_renderer(tool_name: str) -> ToolRenderer | None:
    """Get the registered renderer for a tool."""
    return _tool_renderers.get(tool_name)


def get_all_tool_renderers() -> dict[str, ToolRenderer]:
    """Get all registered tool renderers."""
    return dict(_tool_renderers)


def default_render_tool(params: Any, result: Any, is_streaming: bool = False) -> ToolRenderResult:
    """Default tool renderer — returns JSON representation."""
    import json

    parts: list[str] = []
    if params:
        try:
            parts.append(f"Input: {json.dumps(params, indent=2)}")
        except Exception:
            parts.append(f"Input: {params}")

    if result:
        content = result.get("content", []) if isinstance(result, dict) else []
        texts = [c.get("text", "") for c in content if isinstance(c, dict) and c.get("type") == "text"]
        if texts:
            parts.append(f"Output: {chr(10).join(texts)}")

    return ToolRenderResult(content="\n".join(parts) if parts else "(no content)")
