"""
Playwright smoke test for the admin launcher test page.
- Opens http://localhost:8765/demo/admin-launcher-test.html
- Waits for the 9-button grid
- Clicks each button
- Verifies the click handler runs without error
- Reports pass/fail

Run with: python3 scripts/playwright-launcher-test.py
"""
import asyncio
import sys
from playwright.async_api import async_playwright


async def main():
    url = "http://localhost:8765/demo/admin-launcher-test.html"
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            executable_path="/root/.cache/ms-playwright/chromium-1223/chrome-linux/chrome",
            args=["--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu"],
            timeout=10000,
        )
        context = await browser.new_context()
        page = await context.new_page()

        # Capture console errors
        errors = []
        page.on("pageerror", lambda e: errors.append(f"pageerror: {e}"))
        page.on("console", lambda m: errors.append(f"console.{m.type}: {m.text}"))

        print(f"opening {url}...")
        try:
            await page.goto(url, wait_until="networkidle", timeout=10000)
        except Exception as e:
            print(f"  ✗ goto failed: {e}")
            sys.exit(1)

        # Wait a bit for module imports to settle
        await page.wait_for_timeout(500)

        # Print all console + page errors so we can debug
        print(f"  console events so far: {len(errors)}")
        for e in errors[:10]:
            print(f"    {e}")

        # Wait for the grid to populate
        try:
            await page.wait_for_selector("#buttonGrid .btn", timeout=5000)
        except Exception:
            print(f"  ✗ grid never populated. Full error log:")
            for e in errors:
                print(f"    {e}")
            # Also dump the page HTML
            html = await page.content()
            print(f"  page HTML (first 1000 chars): {html[:1000]}")
            sys.exit(1)
        buttons = await page.query_selector_all("#buttonGrid .btn")
        print(f"  found {len(buttons)} buttons")

        if len(buttons) < 9:
            print(f"  ✗ expected at least 9 buttons, got {len(buttons)}")
            sys.exit(1)

        # Click each non-"open all" button (skip the last "open all" button)
        clicked = 0
        for i, btn in enumerate(buttons[:-1]):  # skip last
            try:
                # Close any open panel from the previous click
                # The "open all" button at the end tests that
                await page.evaluate("""() => {
                    const panels = document.querySelectorAll('[data-panel-id]');
                    panels.forEach(p => p.remove());
                }""")
                await btn.click()
                clicked += 1
                await page.wait_for_timeout(150)
            except Exception as e:
                print(f"  ✗ button {i} click failed: {e}")
                sys.exit(1)

        print(f"  ✓ clicked {clicked} panel buttons")

        # Check the output log has at least 9 "✓ opened panel" lines
        output = await page.text_content("#output")
        opened_count = output.count("opened panel")
        print(f"  output log: {opened_count} 'opened panel' entries")

        if opened_count < 9:
            print(f"  ✗ expected at least 9 opened panels, got {opened_count}")
            print(f"  output:\n{output[:500]}")
            sys.exit(1)

        # Take a screenshot
        await page.screenshot(path="/workspace/freshvibe-cms/demo/admin-launcher-test.png", full_page=True)
        print(f"  ✓ screenshot saved to demo/admin-launcher-test.png")

        # Check for JS errors (filter out favicon 404s — not real bugs)
        real_errors = [e for e in errors if "favicon" not in e.lower() and "404" not in e]
        if real_errors:
            print(f"  ✗ {len(real_errors)} JS errors:")
            for e in real_errors[:5]:
                print(f"    {e}")
            sys.exit(1)

        print(f"\n— {clicked} buttons clicked, {opened_count} panels opened, 0 JS errors —")
        await browser.close()


if __name__ == "__main__":
    asyncio.run(main())
