"""
MCP Plugin: Extensions — wires event_bus, plugin_system, data_export,
integration_hub, specialization (remaining), webhooks (MCP side).
"""

from mcp.types import TextContent


def get_tools():
    return [
        # ── Event Bus ──────────────────────────────────────────────
        {
            "name": "broker_emit_event",
            "description": "Emit an event to the platform event bus. All subscribers receive it.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "event_type": {"type": "string", "description": "e.g. task.created, agent.joined"},
                    "payload": {"type": "object", "default": {}},
                },
                "required": ["event_type"],
            },
        },
        {
            "name": "broker_event_log",
            "description": "Get recent events from the event bus log.",
            "inputSchema": {
                "type": "object",
                "properties": {"limit": {"type": "integer", "default": 20}},
            },
        },
        # ── Plugin System ──────────────────────────────────────────
        {
            "name": "broker_list_plugins",
            "description": "List all registered platform plugins.",
            "inputSchema": {"type": "object", "properties": {}},
        },
        {
            "name": "broker_plugin_stats",
            "description": "Get stats for a specific plugin.",
            "inputSchema": {
                "type": "object",
                "properties": {"plugin_id": {"type": "string"}},
                "required": ["plugin_id"],
            },
        },
        # ── Data Export (GDPR) ─────────────────────────────────────
        {
            "name": "broker_export_data",
            "description": "Export all data for an agent (GDPR compliance).",
            "inputSchema": {
                "type": "object",
                "properties": {"agent_id": {"type": "string"}},
                "required": ["agent_id"],
            },
        },
        {
            "name": "broker_delete_data",
            "description": "Delete all data for an agent (right to be forgotten).",
            "inputSchema": {
                "type": "object",
                "properties": {"agent_id": {"type": "string"}},
                "required": ["agent_id"],
            },
        },
        # ── Specialization ─────────────────────────────────────────
        {
            "name": "broker_analyze_strengths",
            "description": "Analyze an agent's performance history to identify strengths and weaknesses.",
            "inputSchema": {
                "type": "object",
                "properties": {"agent_id": {"type": "string"}},
                "required": ["agent_id"],
            },
        },
        {
            "name": "broker_get_archetype",
            "description": "Get an agent's natural archetype (builder, guardian, architect, fixer, generalist).",
            "inputSchema": {
                "type": "object",
                "properties": {"agent_id": {"type": "string"}},
                "required": ["agent_id"],
            },
        },
        {
            "name": "broker_find_specialist",
            "description": "Find the best specialist agent for a given task category.",
            "inputSchema": {
                "type": "object",
                "properties": {"category": {"type": "string"}},
                "required": ["category"],
            },
        },
        # ── Webhooks (MCP side) ────────────────────────────────────
        {
            "name": "broker_register_webhook",
            "description": "Register a webhook endpoint to receive platform events.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "url": {"type": "string"},
                    "events": {"type": "array", "items": {"type": "string"}, "description": "Event types or ['*'] for all"},
                    "secret": {"type": "string", "default": ""},
                },
                "required": ["url", "events"],
            },
        },
        {
            "name": "broker_list_webhooks",
            "description": "List all registered webhook endpoints.",
            "inputSchema": {"type": "object", "properties": {}},
        },
        {
            "name": "broker_webhook_stats",
            "description": "Get webhook delivery statistics.",
            "inputSchema": {"type": "object", "properties": {}},
        },
    ]


async def handle_tool(name: str, args: dict) -> list[TextContent]:
    import asyncio
    import json

    # ── Event Bus ──────────────────────────────────────────────
    if name == "broker_emit_event":
        from brynq.event_bus import emit
        result = await asyncio.to_thread(emit, args["event_type"], args.get("payload", {}))
        return [TextContent(type="text", text=f"Event emitted: {args['event_type']}")]

    elif name == "broker_event_log":
        from brynq.event_bus import get_event_log
        events = await asyncio.to_thread(get_event_log, limit=args.get("limit", 20))
        if not events:
            return [TextContent(type="text", text="No events in log.")]
        lines = [f"[{e.get('timestamp', '')}] {e.get('event_type', '')} — {str(e.get('payload', ''))[:100]}" for e in events[-10:]]
        return [TextContent(type="text", text=f"Recent events ({len(events)} total):\n" + "\n".join(lines))]

    # ── Plugin System ──────────────────────────────────────────
    elif name == "broker_list_plugins":
        from brynq.plugin_system import list_plugins
        plugins = await asyncio.to_thread(list_plugins)
        if not plugins:
            return [TextContent(type="text", text="No plugins registered.")]
        lines = [f"  {p.get('name', '?')} ({p.get('status', '?')})" for p in plugins]
        return [TextContent(type="text", text=f"Plugins ({len(plugins)}):\n" + "\n".join(lines))]

    elif name == "broker_plugin_stats":
        from brynq.plugin_system import get_plugin_stats
        stats = await asyncio.to_thread(get_plugin_stats, args["plugin_id"])
        return [TextContent(type="text", text=json.dumps(stats, indent=2))]

    # ── Data Export ────────────────────────────────────────────
    elif name == "broker_export_data":
        from brynq.data_export import export_user_data
        data = await asyncio.to_thread(export_user_data, args["agent_id"])
        return [TextContent(type="text", text=f"Exported {len(json.dumps(data))} bytes of data for {args['agent_id']}.")]

    elif name == "broker_delete_data":
        from brynq.data_export import delete_user_data
        result = await asyncio.to_thread(delete_user_data, args["agent_id"])
        return [TextContent(type="text", text=f"Data deletion result: {json.dumps(result)}")]

    # ── Specialization ─────────────────────────────────────────
    elif name == "broker_analyze_strengths":
        from brynq.specialization import analyze_strengths
        result = await asyncio.to_thread(analyze_strengths, args["agent_id"])
        strengths = result.get("strengths", [])
        if not strengths:
            return [TextContent(type="text", text=f"No performance data for {args['agent_id']} yet.")]
        lines = [f"  {s['category']}: score {s['strength_score']} (avg {s['avg_rating']}, {s['tasks_completed']} tasks)" for s in strengths[:5]]
        return [TextContent(type="text", text=f"Strengths for {args['agent_id']}:\n" + "\n".join(lines))]

    elif name == "broker_get_archetype":
        from brynq.specialization import get_agent_archetype
        result = await asyncio.to_thread(get_agent_archetype, args["agent_id"])
        return [TextContent(type="text", text=f"Archetype: {result['archetype']} (confidence: {result.get('confidence', 0)})")]

    elif name == "broker_find_specialist":
        from brynq.specialization import find_specialist
        results = await asyncio.to_thread(find_specialist, args["category"])
        if not results:
            return [TextContent(type="text", text=f"No specialists found for '{args['category']}'.")]
        lines = [f"  {r['session_id']}: score {r['strength_score']} ({r['archetype']})" for r in results[:5]]
        return [TextContent(type="text", text=f"Specialists for '{args['category']}':\n" + "\n".join(lines))]

    # ── Webhooks ───────────────────────────────────────────────
    elif name == "broker_register_webhook":
        from brynq.webhooks import register_endpoint
        result = await asyncio.to_thread(register_endpoint, args["url"], args["events"], secret=args.get("secret", ""))
        if "error" in result:
            return [TextContent(type="text", text=f"Error: {result['error']}")]
        return [TextContent(type="text", text=f"Webhook registered: {result['endpoint_id']} -> {args['url']}")]

    elif name == "broker_list_webhooks":
        from brynq.webhooks import list_endpoints
        eps = await asyncio.to_thread(list_endpoints)
        if not eps:
            return [TextContent(type="text", text="No webhooks registered.")]
        lines = [f"  [{ep['endpoint_id']}] {ep['url']} ({', '.join(ep.get('events', []))})" for ep in eps]
        return [TextContent(type="text", text=f"Webhooks ({len(eps)}):\n" + "\n".join(lines))]

    elif name == "broker_webhook_stats":
        from brynq.webhooks import get_webhook_stats
        stats = await asyncio.to_thread(get_webhook_stats)
        return [TextContent(type="text", text=json.dumps(stats, indent=2))]

    return [TextContent(type="text", text=f"Unknown tool: {name}")]
