/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const notebook = (outputs: unknown[]) => JSON.stringify({
  nbformat: 4, nbformat_minor: 5,
  metadata: { language_info: { name: "python" } },
  cells: [{ id: "steps", cell_type: "code", metadata: {}, execution_count: 1,
    source: ["import time\n", "for i in range(150):\n", "    print(f'step {i}', flush=True)\n", "    time.sleep(0.2)"], outputs }],
});

test("Consecutive stdout records count as one preview output", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("notebook-demo", {
    "steps.ipynb": notebook(Array.from({ length: 150 }, (_, i) => ({ output_type: "stream", name: "stdout", text: [`step ${i}\n`] }))),
    "displays.ipynb": notebook(Array.from({ length: 101 }, (_, i) => ({ output_type: "display_data", metadata: {}, data: { "text/plain": [`result ${i}`] } }))),
  });
  const thread = await t3.thread({ project, title: "Review notebook outputs", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1080 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("displays.ipynb");
  await screen.getByRole("option", "displays.ipynb", { exact: false }).tap();
  await screen.getByText("A notebook cell has too many outputs to preview.", { exact: false }).waitFor();
  await app.screenshot("101-separate-display-results");
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("steps.ipynb");
  await screen.getByRole("option", "steps.ipynb", { exact: false }).tap();
  await expect.poll(() => browser.evaluate(() => {
    const text = document.body.innerText;
    return text.includes("step 149") || text.includes("A notebook cell has too many outputs to preview.");
  })).toBe(true);
  await browser.evaluate(async () => {
    if (!document.body.innerText.includes("Loading code...")) return;
    await new Promise<void>((resolve) => {
      const observer = new MutationObserver(() => {
        if (!document.body.innerText.includes("Loading code...")) {
          observer.disconnect();
          resolve();
        }
      });
      observer.observe(document.body, { subtree: true, childList: true, characterData: true });
    });
  });
  await app.screenshot("150-consecutive-stdout-records");
  expect(await browser.evaluate(() => {
    const outputs = document.querySelectorAll('section[aria-label="Cell 1"] pre');
    const streams = [...outputs].filter((output) => output.textContent?.includes("step 149"));
    return streams.length === 1 && streams[0]?.textContent?.split("\n").filter(Boolean).length === 150 && streams[0]?.textContent?.startsWith("step 0\n");
  })).toBe(true);
});
