from loguru import logger
from playwright.async_api import ConsoleMessage, Page

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

class MarkDownCore:
    @staticmethod
    async def render_markdown(markdown_text: str, theme: str = "dark", params: dict = {}) -> bytes:
        async def page_function(page: Page):
            await page.emulate_media(color_scheme=theme)

            await page.locator('textarea[name=content]').fill(markdown_text)
            await page.locator('#button').click()
            
            # 等待 checkState 函数加载完成
            await page.wait_for_function("typeof checkState === 'function'", timeout=1000)
            # 访问 checkState 函数，确保渲染完成
            await page.wait_for_function("checkState() === true", timeout=1000)

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

        return out
    
    @staticmethod
    async def render_latex(text: str, theme: str = "dark") -> bytes:
        params = {
            "size": "2.5em",
        }
        async def page_function(page: Page):
            await page.emulate_media(color_scheme=theme)

            page.wait_for_selector('textarea[name=content]')
            await page.locator('textarea[name=content]').fill(f"$$ {text} $$")
            page.wait_for_selector('#button')
            await page.locator('#button').click()
            
            # 等待 checkState 函数加载完成
            await page.wait_for_function("typeof checkState === 'function'", timeout=2000)
            # 访问 checkState 函数，确保渲染完成
            await page.wait_for_function("checkState() === true", timeout=10000)

        out = await WebRenderer.render_with_persistent_page(
            "latex_renderer",
            konaweb('latex'),
            target='#main',
            other_function=page_function,
            params=params
        )

        return out