from typing import Optional
from modules.channels.base import BaseChannelAdapter, ChannelType
from modules.channels.telegram import TelegramChannelAdapter
from modules.channels.discord import DiscordChannelAdapter
from modules.channels.webhooks import GenericWebhookChannelAdapter


class ChannelRegistry:
    """
    Central registry for multi-channel communication adapters.
    Enables universal bot dispatch across Telegram, Discord, and Webhooks.
    """

    def __init__(self):
        self._adapters: dict[ChannelType, type[BaseChannelAdapter]] = {
            ChannelType.TELEGRAM: TelegramChannelAdapter,
            ChannelType.DISCORD: DiscordChannelAdapter,
            ChannelType.WEBHOOK: GenericWebhookChannelAdapter,
        }

    def register(self, channel: ChannelType, adapter_cls: type[BaseChannelAdapter]):
        self._adapters[channel] = adapter_cls

    def get_adapter(
        self,
        channel: ChannelType | str,
        token: Optional[str] = None,
        secret: Optional[str] = None,
    ) -> BaseChannelAdapter:
        if isinstance(channel, str):
            try:
                channel = ChannelType(channel.lower())
            except ValueError:
                # Default fallback to Telegram
                channel = ChannelType.TELEGRAM

        adapter_cls = self._adapters.get(channel)
        if not adapter_cls:
            raise ValueError(f"No adapter registered for channel '{channel}'")

        if channel == ChannelType.TELEGRAM:
            return TelegramChannelAdapter(bot_token=token)
        elif channel == ChannelType.DISCORD:
            return DiscordChannelAdapter(bot_token=token)
        elif channel == ChannelType.WEBHOOK:
            return GenericWebhookChannelAdapter(secret=secret)

        return adapter_cls()


# Global Singleton
_CHANNEL_REGISTRY = ChannelRegistry()


def get_channel_registry() -> ChannelRegistry:
    return _CHANNEL_REGISTRY
