"""Render MCP tool inputSchema as human-readable usage text.

Reads JSON Schema from list_tools results and generates rich panels
with parameter descriptions, types, required/optional markers, defaults,
enum values, and example CLI commands.
"""

import json
import sys

from rich.console import Console
from rich.panel import Panel
from rich.text import Text

stdout_console = Console(file=sys.stdout)


def render_tool_detail(tool) -> None:
    """Render a single tool's full schema as a rich panel."""
    lines: list[str] = []

    if tool.description:
        for line in tool.description.strip().split("\n"):
            lines.append(f"  {line.strip()}")
        lines.append("")

    schema = tool.inputSchema or {}
    properties = schema.get("properties", {})
    required_fields = set(schema.get("required", []))

    if properties:
        lines.append("  [bold]Parameters:[/bold]")
        for prop_name, prop_schema in properties.items():
            is_required = prop_name in required_fields
            ptype = prop_schema.get("type", "any")
            desc = prop_schema.get("description", "")
            default = prop_schema.get("default")
            enum_vals = prop_schema.get("enum")

            marker = "[red]REQUIRED[/red]" if is_required else "optional"
            type_str = f"({ptype})"
            default_str = f", default: {default}" if default is not None else ""
            enum_str = f", one of: {enum_vals}" if enum_vals else ""

            lines.append(f"    [cyan]●[/cyan] [bold]{prop_name}[/bold] {type_str} {marker}{default_str}{enum_str}")
            if desc:
                lines.append(f"      {desc}")
        lines.append("")

    lines.append("  [bold]Examples:[/bold]")

    example_args: dict = {}
    for prop_name, prop_schema in properties.items():
        ptype = prop_schema.get("type", "string")
        default = prop_schema.get("default")
        enum_vals = prop_schema.get("enum")
        if enum_vals:
            example_args[prop_name] = enum_vals[0]
        elif default is not None:
            example_args[prop_name] = default
        elif ptype == "string":
            example_args[prop_name] = "VALUE"
        elif ptype == "integer":
            example_args[prop_name] = 10
        elif ptype == "number":
            example_args[prop_name] = 1.0
        elif ptype == "boolean":
            example_args[prop_name] = True
        else:
            example_args[prop_name] = "VALUE"

    kv_parts = " ".join(f"{k}={v}" for k, v in example_args.items())
    json_str = json.dumps(example_args)

    lines.append(f"    [dim]mcpbundles call {tool.name} {kv_parts}[/dim]")
    lines.append(f"    [dim]mcpbundles call {tool.name} '{json_str}'[/dim]")

    if tool.name == "code_execution":
        lines.append(f'    [dim]mcpbundles exec "result = await my_tool(); print(result)"[/dim]')
        lines.append(f"    [dim]mcpbundles exec -f script.py[/dim]")

    content = "\n".join(lines)

    panel = Panel(
        content,
        title=tool.name,
        border_style="cyan",
        padding=(1, 2),
    )
    stdout_console.print(panel)
