"""Browser page helpers for CDP-backed scraping."""

from __future__ import annotations

import asyncio


async def new_background_page(ctx, url="about:blank"):
    """Create a Chromium tab without activating the browser window when possible."""
    browser = getattr(ctx, "browser", None)
    if callable(browser):
        browser = browser()

    new_cdp_session = getattr(browser, "new_browser_cdp_session", None)
    expect_page = getattr(ctx, "expect_page", None)
    if not callable(new_cdp_session) or not callable(expect_page):
        return await ctx.new_page()

    session = None
    try:
        session = await new_cdp_session()
        async with ctx.expect_page() as page_info:
            await session.send(
                "Target.createTarget",
                {
                    "url": url,
                    "background": True,
                    "newWindow": False,
                },
            )
        return await page_info.value
    except Exception:
        return await ctx.new_page()
    finally:
        if session is not None:
            detach = getattr(session, "detach", None)
            if callable(detach):
                try:
                    await detach()
                except Exception:
                    pass


async def close_page_quietly(page):
    try:
        await page.close()
    except Exception:
        pass
