from loguru import logger
import nonebot
from nonebot.adapters import Event as BaseEvent
from nonebot.adapters.discord.event import MessageEvent as DiscordMessageEvent
from nonebot_plugin_alconna import (
    UniMessage,
    UniMsg
)

from konabot.plugins.markdown.core import MarkDownCore

def is_markdown_mentioned(msg: UniMsg) -> bool:
    txt = msg.extract_plain_text()
    if "markdown" not in txt[:8] and "md" not in txt[:2]:
        return False
    return True

evt = nonebot.on_message(rule=is_markdown_mentioned)

@evt.handle()
async def _(msg: UniMsg, event: BaseEvent):
    if isinstance(event, DiscordMessageEvent):
        content = msg.extract_plain_text()
    else:
        content = msg.extract_plain_text()

    logger.debug(f"Received markdown command with content: {content}")
    if "md" in content[:2]:
        message = content.replace("md", "", 1).strip()
    else:
        message = content.replace("markdown", "", 1).strip()
    # 如果回复了消息，则转换回复的内容
    if(len(message) == 0):
        if event.reply:
            message = event.reply.message.extract_plain_text()
        else:
            return
    logger.debug(f"Markdown content to render: {message}")

    out = await MarkDownCore.render_markdown(message, theme="dark")

    await evt.send(await UniMessage().image(raw=out).export())


def is_latex_mentioned(evt: BaseEvent, msg: UniMsg) -> bool:
    txt = msg.extract_plain_text()
    if "latex" not in txt[:5]:
        return False
    return True

evt = nonebot.on_message(rule=is_latex_mentioned)

@evt.handle()
async def _(msg: UniMsg, event: BaseEvent):
    if isinstance(event, DiscordMessageEvent):
        content = msg.extract_plain_text()
    else:
        content = msg.extract_plain_text()

    logger.debug(f"Received markdown command with content: {content}")
    message = content.replace("latex", "", 1).strip()
    # 如果回复了消息，则转换回复的内容
    if(len(message) == 0):
        if event.reply:
            message = event.reply.message.extract_plain_text()
        else:
            return
    logger.debug(f"Latex content to render: {message}")

    out = await MarkDownCore.render_latex(message, theme="dark")

    await evt.send(await UniMessage().image(raw=out).export())
