from typing import List, Union

import discord
from redbot.core import app_commands, commands

from ..models.type import Type, type_registry
from .config import config
from .utils import check_moddable


async def moderate(ctx: Union[commands.Context, discord.Interaction], target: discord.Member | discord.User | discord.abc.Messageable, silent: bool | None, permissions: List[str], moderation_type: Type | str, **kwargs) -> None | Type:
    """This function is used to moderate users.
    It checks if the target can be moderated, then calls the handler method of the moderation type specified.

    Args:
        ctx (Union[commands.Context, discord.Interaction]): The context of the command. If this is a `discord.Interaction` object, it will be converted to a `commands.Context` object. Additionally, if the interaction orignated from a context menu, the `ctx.author` attribute will be overriden to `interaction.user`.
        target (discord.Member, discord.User, discord.abc.Messageable): The target user or channel to moderate.
        silent (bool | None): Whether to send the moderation action to the target.
        permissions (List[str]): The permissions required to moderate the target.
        moderation_type (Type): The moderation type (handler) to use. See `aurora.models.moderation_types` for some examples.
        **kwargs: The keyword arguments to pass to the handler method.
    """
    if isinstance(moderation_type, str):
        moderation_type = type_registry[str.lower(moderation_type)]
    if isinstance(ctx, discord.Interaction):
        interaction = ctx
        ctx = await commands.Context.from_interaction(interaction)
        if isinstance(interaction.command, app_commands.ContextMenu):
            ctx.author = interaction.user
    if not await check_moddable(target=target, ctx=ctx, permissions=permissions, moderation_type=moderation_type):
        return
    if silent is None:
        dm_users = await config.custom("types", ctx.guild.id, moderation_type.key).dm_users()
        if dm_users is None:
            dm_users = await config.guild(ctx.guild).dm_users()
        silent = not dm_users
    return await moderation_type.handler(
        ctx=ctx,
        target=target,
        silent=silent,
        **kwargs
    )
