"""Kommunikation plugin — unified messaging: chat, AI, system, messenger."""

from __future__ import annotations

import logging
from typing import Any

from app.plugins.base import BasePlugin
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute

logger = logging.getLogger(__name__)


class KommunikationPlugin(BasePlugin):
    """Unified messaging plugin: conversations, messages, participants, WebSocket, rich content."""

    manifest = PluginManifest(
        name="kommunikation",
        version="1.0.0",
        display_name="Kommunikation",
        description=(
            "Unified Messaging: Chat, KI, System, Messenger — "
            "alles ist ein Teilnehmer."
        ),
        dependencies=["permissions", "dms"],
        routes=[
            PluginRouteDef(
                path="/api/v1/comm",
                module="app.plugins.builtins.kommunikation.routes",
                router_attr="router",
            ),
        ],
        events=[
            "message.received",
            "message.sent",
            "conversation.created",
            "conversation.updated",
            "participant.joined",
            "participant.left",
            "reaction.added",
        ],
        migrations=["0001_initial.sql"],
        permissions=[
            "comm:read",
            "comm:write",
            "comm:create",
            "comm:manage",
            "comm:admin",
            "comm:delete",
        ],
        is_core=True,
        menu_items=[
            FrontendMenuItem(label_key='nav.communication', label='Communication', path='/communication', icon='MessageSquare', order=80),
        ],
        page_routes=[
            FrontendPageRoute(path='/communication', component='@/pages/Communication', protected=True),
        ],
    )

    async def on_activate(self, db, service_container, event_bus) -> None:
        """Register participant registry and WebSocket manager."""
        await super().on_activate(db, service_container, event_bus)

        # Register WebSocket manager as a shared service
        from app.plugins.builtins.kommunikation.websocket_manager import WebSocketManager
        ws_manager = WebSocketManager()
        service_container.register("comm_websocket", ws_manager)

        # Register Mini-App registry as a shared service
        from app.plugins.builtins.kommunikation.miniapp_registry import MiniAppRegistry
        miniapp_registry = MiniAppRegistry()
        service_container.register("comm_miniapps", miniapp_registry)

        logger.info("Kommunikation plugin activated — WebSocket + MiniApp registries ready")

    async def on_deactivate(self, db, service_container, event_bus) -> None:
        """Clean up registries."""
        await super().on_deactivate(db, service_container, event_bus)
        logger.info("Kommunikation plugin deactivated")

    def get_notification_types(self) -> list[dict[str, Any]]:
        return [
            {
                "type_key": "comm_message",
                "category": "communication",
                "label": "Neue Nachricht",
                "description": "Neue Nachricht in einer Konversation",
                "is_enabled_by_default": True,
            },
            {
                "type_key": "comm_mention",
                "category": "communication",
                "label": "Erwähnung",
                "description": "Du wurdest in einer Nachricht erwähnt",
                "is_enabled_by_default": True,
            },
        ]
