"""MCP status view for displaying server and tool information."""

import logging
from typing import Dict, Any, List

from core.ui.design_system import T, S, solid, solid_fg
from core.io.terminal_state import get_global_width


logger = logging.getLogger(__name__)


class MCPStatusView:
    """
    Status view for MCP (Model Context Protocol) integration.

    Displays connected MCP servers and their available tools
    in a formatted status panel.
    """

    def __init__(
        self,
        mcp_integration,
    ):
        """Initialize MCP status view.

        Args:
            mcp_integration: MCPIntegration instance
        """
        self._mcp_integration = mcp_integration

    def render(self) -> List[str]:
        """
        Render the MCP status panel.

        Returns:
            List of formatted lines to display
        """
        from core.ui.design_system import TagBox

        width = get_global_width()

        # Build content lines
        content_lines = []

        # Header line
        header = f"{S.BOLD}MCP SERVERS{S.RESET_BOLD}"

        # Get server information
        connections = self._mcp_integration.server_connections
        tool_registry = self._mcp_integration.tool_registry
        mcp_servers = self._mcp_integration.mcp_servers

        # Count statistics
        total_servers = len(mcp_servers)
        connected_servers = len(connections)
        total_tools = len(tool_registry)

        # Build status line
        status_text = f"{connected_servers}/{total_servers} servers | {total_tools} tools"

        # Calculate padding
        visible_header = "MCP SERVERS"
        padding = width - len(visible_header) - len(status_text) - 8
        header_line = f"{header}{' ' * max(1, padding)}{status_text}"
        content_lines.append(header_line)

        # Add server details if any are connected
        if connections:
            content_lines.append("")  # Blank line

            # Group tools by server
            server_tools: Dict[str, List[str]] = {}
            for tool_name, tool_info in tool_registry.items():
                server_name = tool_info.get("server", "unknown")
                if server_name not in server_tools:
                    server_tools[server_name] = []
                server_tools[server_name].append(tool_name)

            # Add each server
            for server_name, tools in sorted(server_tools.items()):
                connection = connections.get(server_name)
                if connection and connection.initialized:
                    # Server status
                    status_icon = "+"
                    tool_count = len(tools)
                    server_line = f"{status_icon} {server_name}: {tool_count} tools"
                    content_lines.append(server_line)

                    # Add first few tools as examples
                    sample_tools = sorted(tools)[:3]
                    for tool in sample_tools:
                        content_lines.append(f"  - {tool}")

                    if tool_count > 3:
                        content_lines.append(f"  ... and {tool_count - 3} more")

        elif total_servers == 0:
            content_lines.append("")
            content_lines.append("No MCP servers configured")
            content_lines.append("See: docs/mcp/MCP_SETUP.md")

        else:
            content_lines.append("")
            content_lines.append("No servers connected")
            content_lines.append("Check configuration")

        # Render using TagBox with primary colors
        rendered = TagBox.render(
            lines=content_lines,
            tag_bg=T().primary[0],
            tag_fg=T().text_dark,
            tag_width=3,
            content_colors=T().dark,
            content_fg=T().text,
            content_width=width - 3,
            tag_chars=[" > ", "   ", "   "],
        )

        return rendered.split("\n")


class MCPToolDetailView:
    """
    Detailed view for a specific MCP tool.

    Shows tool description, parameters, and server information.
    """

    def __init__(
        self,
        tool_name: str,
        tool_info: Dict[str, Any],
    ):
        """Initialize MCP tool detail view.

        Args:
            tool_name: Name of the tool
            tool_info: Tool information dictionary
        """
        self._tool_name = tool_name
        self._tool_info = tool_info

    def render(self) -> List[str]:
        """
        Render the tool detail panel.

        Returns:
            List of formatted lines to display
        """
        from core.ui.design_system import TagBox

        width = get_global_width()

        # Build content lines
        content_lines = []

        # Header line
        header = f"{S.BOLD}MCP TOOL{S.RESET_BOLD}"

        # Tool name and server
        server_name = self._tool_info.get("server", "unknown")
        server_line = f"@ {server_name}"

        # Calculate padding
        visible_header = "MCP TOOL"
        padding = width - len(visible_header) - len(server_line) - len(self._tool_name) - 8
        header_line = f"{header} {self._tool_name}{' ' * max(1, padding)}{server_line}"
        content_lines.append(header_line)

        # Tool description
        definition = self._tool_info.get("definition", {})
        description = definition.get("description", "No description")
        content_lines.append("")
        content_lines.append(description)

        # Tool parameters
        parameters = definition.get("parameters", {})
        if parameters and parameters.get("properties"):
            content_lines.append("")
            content_lines.append(f"{S.BOLD}Parameters:{S.RESET_BOLD}")

            for param_name, param_info in parameters.get("properties", {}).items():
                param_type = param_info.get("type", "unknown")
                param_desc = param_info.get("description", "")
                required = param_name in parameters.get("required", [])
                req_marker = "*" if required else ""

                content_lines.append(f"  {param_name}{req_marker}: {param_type}")
                if param_desc:
                    content_lines.append(f"    {param_desc}")

            if parameters.get("required"):
                content_lines.append("")
                content_lines.append("* = required")

        # Render using TagBox
        rendered = TagBox.render(
            lines=content_lines,
            tag_bg=T().primary[0],
            tag_fg=T().text_dark,
            tag_width=3,
            content_colors=T().dark,
            content_fg=T().text,
            content_width=width - 3,
            tag_chars=[" * ", "   ", "   "],
        )

        return rendered.split("\n")


def render_mcp_status(mcp_integration) -> List[str]:
    """
    Convenience function to render MCP status.

    Args:
        mcp_integration: MCPIntegration instance

    Returns:
        List of formatted lines
    """
    view = MCPStatusView(mcp_integration)
    return view.render()


def render_mcp_tool_detail(tool_name: str, tool_info: Dict[str, Any]) -> List[str]:
    """
    Convenience function to render MCP tool detail.

    Args:
        tool_name: Name of the tool
        tool_info: Tool information dictionary

    Returns:
        List of formatted lines
    """
    view = MCPToolDetailView(tool_name, tool_info)
    return view.render()
