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

test("Saved IPython traceback is readable without terminal escape codes", WEB, async ({ t3, app, screen, browser }) => {
  const notebook = {
    nbformat: 4, nbformat_minor: 5,
    metadata: { kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, language_info: { name: "python" } },
    cells: [{ cell_type: "code", id: "division", metadata: {}, execution_count: 1, source: ["1 / 0"], outputs: [{ output_type: "error", ename: "ZeroDivisionError", evalue: "division by zero", traceback: [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mZeroDivisionError\u001b[39m                         Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m \u001b[36mIn[1]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> 1\u001b[39m 1 / 0",
      "\u001b[31mZeroDivisionError\u001b[39m: division by zero"
    ] }] }]
  };
  const project = await t3.project("notebook-demo", { "error.ipynb": JSON.stringify(notebook) });
  const thread = await t3.thread({ project, title: "Notebook review", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  await browser.evaluate(async () => {
    for (let attempt = 0; attempt < 100; attempt++) {
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="error.ipynb"]');
        if (row) { row.click(); return; }
      }
      await new Promise(resolve => setTimeout(resolve, 100));
    }
    throw new Error("Notebook file row not found");
  });
  const output = screen.getByText("division by zero", { exact: false }).last();
  await output.waitFor({ state: "visible", timeout: 120000 });
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await screen.getByText("Loading code...", { exact: true }).waitFor({ state: "hidden", timeout: 30000 });
  await app.screenshot("saved-notebook-traceback");
  await expect(output).not.toContainText("\u001b[");
});
