import re
from nonebot import on_message
from nonebot.rule import StartswithRule
from nonebot_plugin_alconna import At, Text, UniMessage, UniMsg

from konabot.common.longtask import DepLongTaskTarget
from konabot.common.web_render import konaweb
from konabot.common.web_render.core import WebRenderer


evt = on_message(rule=StartswithRule(("k8x12s",), True))
rule = re.compile(r"^[kK]8[xX]12[sS] ?(.+)$")


@evt.handle()
async def _(msg: UniMsg, target: DepLongTaskTarget):
    if len(msg.include(Text, At)) != len(msg):
        return

    text = msg.extract_plain_text()
    result = re.match(rule, text)
    if result is None:
        return

    obj: str | None = result.group(1)
    if obj is None:
        return

    img = await render_with_web_renderer(obj)
    await target.send_message(UniMessage.image(raw=img), at=False)


async def render_with_web_renderer(text: str) -> bytes:
    async def page_function(page):
        await page.wait_for_selector('textarea[name=content]')
        await page.locator('textarea[name=content]').fill(text)

    out = await WebRenderer.render_with_persistent_page(
        "markdown_renderer",
        konaweb('k8x12S'),
        target='#main',
        other_function=page_function,
    )
    return out


