from __future__ import annotations

from typing import Any


class BrowserCDP:
    """Playwright-based headless control (CDP-compatible stack)."""

    async def navigate(
        self, url: str, wait_until: str = "load", timeout_ms: float = 60_000
    ) -> dict[str, Any]:
        try:
            from playwright.async_api import async_playwright
        except ImportError as e:
            return {"ok": False, "error": f"playwright not available: {e}"}
        async with async_playwright() as p:
            browser = await p.chromium.launch(headless=True)
            page = await browser.new_page()
            try:
                await page.goto(url, wait_until=wait_until, timeout=int(timeout_ms))
                title = await page.title()
                content = await page.content()
            finally:
                await browser.close()
        snippet = content[:8000] + ("..." if len(content) > 8000 else "")
        return {
            "ok": True,
            "title": title,
            "url": url,
            "html_snippet": snippet,
        }
