from playwright.async_api import async_playwright

async def get_async_context(browser):
        return await browser.new_context()

async def get_async_page(context):
    return await context.new_page()

async def prepare_browser(browser_type="chromium", headless=True):
    apw = await async_playwright().start()  # Start Playwright manually
    try:
        # Initialize the correct browser
        if browser_type == "firefox":
            browser = await apw.firefox.launch(headless=headless)
        elif browser_type == "chromium" or browser_type == "edge":  # Edge uses Chromium
            browser = await apw.chromium.launch(headless=headless)
        elif browser_type == "webkit":
            browser = await apw.webkit.launch(headless=headless)
        else:
            raise ValueError(f"Unsupported platform: {browser_type}")

        # Create context and page
        context = await browser.new_context()
        page = await context.new_page()

        # Return everything (browser, context, page)
        # return browser, context, page
        return apw, browser, page
        # return browser, page
    except Exception as e:
        # Cleanup Playwright instance upon failure
        await apw.stop()
        raise e


async def cleanup_browser(apw, browser):
    # A utility function to close and clean up resources
    if browser:
        await browser.close()
    if apw:
        await apw.stop()