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

const notebook = (plain: string) => JSON.stringify({
  nbformat: 4, nbformat_minor: 5, metadata: { language_info: { name: "python" } },
  cells: [{ id: "result", cell_type: "code", source: ["display(result)"], metadata: {}, execution_count: 1,
    outputs: [{ output_type: "display_data", metadata: {}, data: { "text/plain": plain, "text/markdown": "**ready**" } }] }],
});

test("Empty plain-text notebook output falls back to saved Markdown", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("notebook-demo", { "results.ipynb": notebook(""), "control.ipynb": notebook("ready") });
  const thread = await t3.thread({ project, title: "Review notebook results", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  for (const file of ["control.ipynb", "results.ipynb"]) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(file);
    await screen.getByRole("option", file, { exact: false }).tap();
    await screen.getByText("Saved outputs only. Code is never executed.", { exact: true }).waitFor();
    await screen.getByText("display(result)", { exact: false }).waitFor();
    if (file === "control.ipynb") {
      await screen.getByText("ready", { exact: true }).waitFor();
      await app.screenshot("nonempty-plain-control");
    }
  }
  try {
    await expect.poll(() => browser.evaluate(() => document.querySelector('section[aria-label="Cell 1"] pre.whitespace-pre-wrap')?.textContent?.trim() ?? "")).toBe("**ready**");
  } finally {
    await app.screenshot("empty-plain-markdown");
  }
});
