from typing import Dict, Optional

from .discord_plugin import handle_discord_action
from .types import ChannelActionContext, ChannelPlugin


def _default_handler(ctx: ChannelActionContext) -> dict:
    if ctx.action not in ("send", "poll", "react", "delete"):
        raise ValueError(f"Action {ctx.action} not supported for channel {ctx.channel}")
    return {
        "ok": True,
        "channel": ctx.channel,
        "action": ctx.action,
        "to": str(ctx.params.get("to", "")),
        "message_id": f"{ctx.channel}-msg-001",
    }


PLUGIN_REGISTRY: Dict[str, ChannelPlugin] = {
    "discord": ChannelPlugin(id="discord", handle_action=handle_discord_action),
    "telegram": ChannelPlugin(id="telegram", handle_action=_default_handler),
    "whatsapp": ChannelPlugin(id="whatsapp", handle_action=_default_handler),
}


def dispatch_channel_message_action(ctx: ChannelActionContext) -> Optional[dict]:
    plugin = PLUGIN_REGISTRY.get(ctx.channel)
    if not plugin:
        return None
    return plugin.handle_action(ctx)

