from typing import Any
from loguru import logger
from nonebot_plugin_alconna import UniMessage
import playwright.async_api
from playwright.async_api import Page

from konabot.common.web_render import WebRenderer, konaweb


async def render_error_message(message: str) -> UniMessage[Any]:
    """
    渲染文本消息为错误信息图片。

    如果无法访达 Web 端则返回纯文本给用户。
    """

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

    try:
        img_data = await WebRenderer.render(
            url=konaweb("error_report"),
            target="#main",
            other_function=page_function,
        )
        return UniMessage.image(raw=img_data)
    except (playwright.async_api.Error, ConnectionError) as e:
        logger.warning("渲染报错信息图片时出错了，回退到文本 ERR={}", e)
        return UniMessage.text(message)

