import sys
import asyncio
from pathlib import Path
from playwright.async_api import async_playwright

HTML_TMPL = """
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"/>
  <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
  <style>
    body { margin: 0; padding: 20px; }
    #container { width: 1800px; }
    .mermaid { font-size: 16px; }
  </style>
  <script>
    mermaid.initialize({ startOnLoad: true, theme: 'default' });
  </script>
</head>
<body>
  <div id="container">
    <div class="mermaid" id="diagram">DIAGRAM_PLACEHOLDER</div>
  </div>
  </body>
</html>
"""

async def render(mermaid_text: str, out_png: Path):
    html = HTML_TMPL.replace("DIAGRAM_PLACEHOLDER", mermaid_text)
    tmp = out_png.with_suffix('.html')
    tmp.write_text(html, encoding='utf-8')
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page(viewport={"width": 2000, "height": 1200})
        await page.goto(tmp.resolve().as_uri(), wait_until="domcontentloaded", timeout=120000)
        await page.wait_for_selector('#diagram', state='attached', timeout=120000)
        await page.evaluate("""
        try { mermaid.initialize({ startOnLoad: false, theme: 'default' }); } catch (e) {}
        """
        )
        await page.evaluate("""
        (async () => {
          try {
            await mermaid.run({ querySelector: '.mermaid' });
            const svg = document.querySelector('.mermaid svg');
            if (svg) { svg.style.width = '1800px'; svg.style.height = 'auto'; svg.style.maxWidth = 'none'; }
          } catch (e) {}
        })();
        """
        )
        await page.wait_for_selector('.mermaid svg', state='attached', timeout=120000)
        elem = await page.query_selector('#container')
        await elem.screenshot(path=str(out_png))
        await browser.close()
    tmp.unlink(missing_ok=True)

def main():
    if len(sys.argv) < 3:
        print('Usage: python -m hos_m2f.render_mermaid <input.mmd> <output.png>')
        sys.exit(1)
    inp = Path(sys.argv[1])
    outp = Path(sys.argv[2])
    text = inp.read_text(encoding='utf-8')
    asyncio.run(render(text, outp))
    print(f'Rendered: {inp} -> {outp}')

if __name__ == '__main__':
    main()

