import re

import nonebot
from nonebot.adapters import Event
from nonebot_plugin_alconna import UniMessage, UniMsg

from konabot.common.nb import match_keyword
from konabot.common.permsys import register_default_allow_permission, require_permission
from konabot.plugins.trpg_roll.core import RollError, roll_expression


PERMISSION_KEY = "trpg.roll"
register_default_allow_permission(PERMISSION_KEY)


matcher = nonebot.on_message(
    rule=match_keyword.match_keyword(re.compile(r"^roll(?:\s+.+)?$", re.I))
    & require_permission(PERMISSION_KEY),
)


@matcher.handle()
async def _(event: Event, msg: UniMsg):
    text = msg.extract_plain_text().strip()
    expr = text[4:].strip()

    if not expr:
        await UniMessage.text("用法：roll 3d6 / roll d20+5 / roll 2d8+1d4+3 / roll 4dF").send(event)
        return

    try:
        result = roll_expression(expr)
        await UniMessage.text(result.format()).send(event)
    except RollError as e:
        await UniMessage.text(str(e)).send(event)
