from typing import Any

from nonebot.adapters import Bot
from nonebot.matcher import Matcher
from nonebot.message import run_postprocessor
from nonebot_plugin_alconna import UniMessage
from returns.primitives.exceptions import UnwrapFailedError

from konabot.common.nb.exc import BotExceptionMessage


@run_postprocessor
async def _(bot: Bot, matcher: Matcher, exc: BotExceptionMessage | AssertionError | UnwrapFailedError):
    if isinstance(exc, BotExceptionMessage):
        msg = exc.msg
        await matcher.send(await msg.export(bot))
    if isinstance(exc, AssertionError):
        if exc.args:
            err_msg = exc.args[0]

            err_msg_res: UniMessage
            if isinstance(err_msg, str):
                err_msg_res = UniMessage().text(err_msg)
            elif isinstance(err_msg, UniMessage):
                err_msg_res = err_msg
            else:
                return

            await matcher.send(await err_msg_res.export(bot))
    if isinstance(exc, UnwrapFailedError):
        obj = exc.halted_container
        try:
            failure: Any = obj.failure()

            err_msg_res: UniMessage
            if isinstance(failure, str):
                err_msg_res = UniMessage().text(failure)
            elif isinstance(failure, UniMessage):
                err_msg_res = failure
            else:
                return

            await matcher.send(await err_msg_res.export(bot))
        except:
            pass
