import type { Page } from "playwright";

export type CapturedScreenshot = {
  bytes: Buffer;
  dimensions: { width: number; height: number };
};

// Playwright derives the fullPage clip from the document scroll box and rejects
// it when either axis collapses; the viewport capture keeps such a page
// observable by detectors instead of failing the cell.
export async function capturePageScreenshotWithDimensions(page: Page): Promise<CapturedScreenshot> {
  const documentBox = await page.evaluate(() => ({
    width: document.documentElement.scrollWidth,
    height: document.documentElement.scrollHeight,
  }));
  if (documentBox.width <= 0 || documentBox.height <= 0) {
    const viewport = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
    return {
      bytes: await page.screenshot({ type: "png" }),
      dimensions: viewport,
    };
  }
  return {
    bytes: await page.screenshot({ type: "png", fullPage: true }),
    dimensions: documentBox,
  };
}

export async function capturePageScreenshot(page: Page): Promise<Buffer> {
  return (await capturePageScreenshotWithDimensions(page)).bytes;
}
