from typing import Dict, Type, Optional

from .channels import ConsoleEventChannel, FileEventChannel, HttpEventChannel, EventChannel
from .core import EventHandler


class EventHandlerFactory:
    _registered_channels: Dict[str, Type[EventChannel]] = {
        "console": ConsoleEventChannel,
        "file": FileEventChannel,
        "http": HttpEventChannel,
    }

    @classmethod
    def register_channel(cls, channel_type: str, channel_class: Type[EventChannel]) -> None:
        """
        Registers a custom channel type to the channel registry.

        :param channel_type: The unique string identifier for the custom channel.
        :param channel_class: The class implementing the EventChannel for this type.
        """
        if not issubclass(channel_class, EventChannel):
            raise TypeError("channel_class must be a subclass of EventChannel")
        cls._registered_channels[channel_type.lower()] = channel_class

    @staticmethod
    def from_config(config: Optional[Dict[str, str]] = None) -> EventHandler:
        """
        Creates an EventHandler instance based on the provided configuration.

        :param config: A dictionary containing configuration properties.
        :return: An EventHandler instance configured with the appropriate channel.
        """
        if config is None:
            config = {}

        channel_type = config.get("EVENTBUS_CHANNEL", "console").lower()
        channel_class = EventHandlerFactory._registered_channels.get(channel_type)

        if channel_class is None:
            raise ValueError(f"Unsupported channel type: {channel_type}")

        channel = channel_class.from_config(config)
        return EventHandler(channel)
