import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const variants = {
  "control-with-traceback": { traceback: ["\u001b[31mZeroDivisionError\u001b[0m: division by zero"] },
  "empty-traceback": { traceback: [] },
  "missing-traceback": {},
  "blank-traceback": { traceback: ["\u001b[31m\u001b[0m", "  \n"] },
};
const files = Object.fromEntries(Object.entries(variants).map(([name, fields]) => [
  `${name}.ipynb`, JSON.stringify({ nbformat: 4, nbformat_minor: 5,
    metadata: { language_info: { name: "python" } }, cells: [
      { id: "before", cell_type: "code", metadata: {}, execution_count: 1,
        source: ["print('before')"], outputs: [{ output_type: "stream", name: "stdout", text: ["before\n"] }] },
      { id: "error", cell_type: "code", metadata: {}, execution_count: 2,
        source: ["1 / 0"], outputs: [{ output_type: "error", ename: "ZeroDivisionError", evalue: "division by zero", ...fields }] },
    ] }),
]));

test("Saved notebook errors remain visible without a usable traceback", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("notebook-errors", files);
  const thread = await t3.thread({ project, title: "Review saved notebook errors", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1080 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  const results: Record<string, string | null> = {};
  for (const name of Object.keys(variants)) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(`${name}.ipynb`);
    await screen.getByRole("option", `${name}.ipynb`, { exact: false }).tap();
    await screen.getByText("2 cells", { exact: false }).waitFor({ timeout: 120_000 });
    await screen.getByRole("region", "Cell 1").getByText("before", { exact: true }).waitFor({ timeout: 120_000 });
    await screen.getByRole("region", "Cell 2").getByText("1 / 0", { exact: true }).waitFor({ timeout: 120_000 });
    await app.screenshot(name);
    results[name] = await browser.evaluate(() => document.querySelector('section[aria-label="Cell 2"] pre')?.textContent?.trim() ?? null);
  }
  expect(results).toEqual(Object.fromEntries(Object.keys(variants).map(name => [name, "ZeroDivisionError: division by zero"])));
});
