import base64
import secrets
from typing import Literal

from nonebot.adapters import Event as BaseEvent
from nonebot.adapters.discord.event import MessageEvent as DiscordMessageEvent
from nonebot_plugin_alconna import (Alconna, Args, Field, Subcommand,
                                    UniMessage, on_alconna)

evt = on_alconna(Alconna(
    "openssl",
    Subcommand(
        "rand",
        Args["mode", Literal["-hex", "-base64"], Field(
            missing_tips=lambda: "请输入生成模式，-hex 或 -base64，例如 openssl rand -hex 16",
            unmatch_tips=lambda mode: f"{mode} 不是一个有效的格式，请使用 -hex 或 -base64"
        )],
        Args["num", int, Field(
            missing_tips=lambda: "请输入需要生成的字节数，例如 openssl rand -hex 16",
        )],
    )
), use_cmd_start=True, use_cmd_sep=False, skip_for_unmatch=False)

@evt.assign("rand")
async def _(event: BaseEvent, mode: str, num: int):
    if num <= 0:
        await evt.send(await UniMessage().text(
            "生成的字节数必须是一个正整数"
        ).export())
        return
    if num > 256:
        await evt.send(await UniMessage().text(
            "太大了！！！！！"
        ).export())
        return

    random_bytes = secrets.token_bytes(num)
    if mode == "-hex":
        result = random_bytes.hex()
    else:
        result = base64.b64encode(random_bytes).decode()

    if isinstance(event, DiscordMessageEvent):
        result = f"```{result}```"

    await evt.send(await UniMessage().text(result).export())
