import re
from typing import Any
from nonebot import on_message
from nonebot.adapters import Event
from nonebot_plugin_alconna import UniMessage, UniMsg
from playwright.async_api import Page

from konabot.common.nb import match_keyword
from konabot.common.web_render import WebRenderer, konaweb


async def render_image(message: str, style: str = 'say') -> UniMessage[Any]:
    """
    渲染文本为图片
    """

    async def page_function(page: Page):
        await page.wait_for_function("typeof setContent === 'function'")
        await page.evaluate(
            "([ message, style ]) => { return setContent(message, style); }",
            [ message, style ],
        )

    img_data = await WebRenderer.render(
        url=konaweb("krgsay"),
        target="#main",
        other_function=page_function,
    )
    return UniMessage.image(raw=img_data)


ALLOWED_STYLE = { "say", "cry", "hungry", "blush" }


cmd = on_message(
    rule=match_keyword.match_keyword(
        re.compile(r"^krg(" + '|'.join(ALLOWED_STYLE) + r")\s.+", re.I),
    ),
)

@cmd.handle()
async def _(event: Event, msg: UniMsg):
    text = msg.extract_plain_text().lstrip()
    command, content = text.split(maxsplit=1)
    style = command.removeprefix("krg").lower()
    if style not in ALLOWED_STYLE:
        style = 'say'
    msg = await render_image(content, style)
    await msg.send(event)

