"""
Example plugin demonstrating MCP plugin capabilities
"""

from typing import Any, Dict, List

from mcp.types import TextContent

from ..utils.logging import log_tool_end, log_tool_start
from ..utils.plugins import ToolPlugin


class ExamplePlugin(ToolPlugin):
    """Example plugin with demonstration tools."""

    def __init__(self):
        super().__init__("example_plugin", "1.0.0")

    def initialize(self, config: dict[str, Any]) -> bool:
        """Initialize the example plugin."""
        # Add example tools
        self.add_tool("example_greet", self.greet_tool)
        self.add_tool("example_calculate", self.calculate_tool)
        self.add_tool("example_data_processor", self.data_processor_tool)

        return True

    async def greet_tool(self, args: dict[str, Any]) -> list[TextContent]:
        """Example greeting tool."""
        start_time = log_tool_start("example_greet", args)

        try:
            name = args.get("name", "World")
            greeting = args.get("greeting", "Hello")

            result = {
                "greeting": f"{greeting}, {name}!",
                "timestamp": "2024-01-01T12:00:00Z",  # Would use real timestamp
                "plugin_info": {
                    "plugin_name": self.name,
                    "plugin_version": self.version,
                },
            }

            log_tool_end("example_greet", start_time, result, True)
            return [TextContent(type="text", text=f"Greeting: {result['greeting']}")]

        except Exception as e:
            log_tool_end("example_greet", start_time, {}, False, str(e))
            return [TextContent(type="text", text=f"Greet failed: {e}")]

    async def calculate_tool(self, args: dict[str, Any]) -> list[TextContent]:
        """Example calculation tool."""
        start_time = log_tool_start("example_calculate", args)

        try:
            operation = args.get("operation", "add")
            a = args.get("a", 0)
            b = args.get("b", 0)

            if operation == "add":
                result_value = a + b
            elif operation == "subtract":
                result_value = a - b
            elif operation == "multiply":
                result_value = a * b
            elif operation == "divide":
                if b == 0:
                    raise ValueError("Division by zero")
                result_value = a / b
            else:
                raise ValueError(f"Unknown operation: {operation}")

            result = {
                "operation": operation,
                "a": a,
                "b": b,
                "result": result_value,
                "plugin_info": {
                    "plugin_name": self.name,
                    "plugin_version": self.version,
                },
            }

            log_tool_end("example_calculate", start_time, result, True)
            return [TextContent(type="text", text=f"Calculation result: {result_value}")]

        except Exception as e:
            log_tool_end("example_calculate", start_time, {}, False, str(e))
            return [TextContent(type="text", text=f"Calculation failed: {e}")]

    async def data_processor_tool(self, args: dict[str, Any]) -> list[TextContent]:
        """Example data processing tool."""
        start_time = log_tool_start("example_data_processor", args)

        try:
            data = args.get("data", [])
            operation = args.get("operation", "count")

            if not isinstance(data, list):
                raise ValueError("Data must be a list")

            if operation == "count":
                result_value = len(data)
            elif operation == "sum":
                try:
                    result_value = sum(float(x) for x in data)
                except (ValueError, TypeError):
                    raise ValueError("All data items must be numbers for sum operation")
            elif operation == "average":
                try:
                    result_value = sum(float(x) for x in data) / len(data) if data else 0
                except (ValueError, TypeError):
                    raise ValueError("All data items must be numbers for average operation")
            elif operation == "unique":
                result_value = len(set(data))
            else:
                raise ValueError(f"Unknown operation: {operation}")

            result = {
                "operation": operation,
                "data_count": len(data),
                "result": result_value,
                "plugin_info": {
                    "plugin_name": self.name,
                    "plugin_version": self.version,
                },
            }

            log_tool_end("example_data_processor", start_time, result, True)
            return [TextContent(type="text", text=f"Data processing result: {result_value}")]

        except Exception as e:
            log_tool_end("example_data_processor", start_time, {}, False, str(e))
            return [TextContent(type="text", text=f"Data processing failed: {e}")]


# Plugin instance (will be loaded by plugin manager)
plugin = ExamplePlugin()
