/// <reference lib="dom" />
import { expect } from "e2e";

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

const ESC = "\u001b";
const notebook = {
  nbformat: 4,
  nbformat_minor: 5,
  metadata: { language_info: { name: "python" } },
  cells: [
    {
      id: "display",
      cell_type: "code",
      source: [],
      metadata: {},
      execution_count: 1,
      outputs: [{ output_type: "display_data", metadata: {}, data: { "text/plain": `${ESC}]0;Analysis\u0007Finished` } }],
    },
    {
      id: "stream",
      cell_type: "code",
      source: [],
      metadata: {},
      execution_count: 2,
      outputs: [{ output_type: "stream", name: "stdout", text: `${ESC}]2;StreamTitle${ESC}\\Stream done\n` }],
    },
    {
      id: "error",
      cell_type: "code",
      source: [],
      metadata: {},
      execution_count: 3,
      outputs: [{ output_type: "error", ename: "ValueError", evalue: `${ESC}]0;ErrTitle\u0007boom`, traceback: [`${ESC}]0;TbTitle\u0007${ESC}[31mValueError${ESC}[0m: boom`] }],
    },
  ],
};

 test(
  "Notebook previews hide terminal title commands in saved output",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("demo", { "analysis.ipynb": JSON.stringify(notebook) });
    await browser.setViewport({ width: 1440, height: 1080 });
    await t3.open();
    await screen.getByTestId("composer-editor").waitFor();
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("analysis.ipynb");
    await screen.getByRole("option", "analysis.ipynb", { exact: false }).tap();
    await screen.getByText("Finished", { exact: false }).waitFor({ timeout: 120_000 });
    await screen.getByText("Saved outputs only. Code is never executed.", { exact: false }).waitFor();
    try {
      await expect.poll(() => browser.evaluate(() => document.body.innerText)).not.toContain("Analysis");
      await expect.poll(() => browser.evaluate(() => document.body.innerText)).not.toContain("StreamTitle");
      await expect.poll(() => browser.evaluate(() => document.body.innerText)).not.toContain("ErrTitle");
      await expect.poll(() => browser.evaluate(() => document.body.innerText)).not.toContain("TbTitle");
    } finally {
      await app.screenshot("notebook-title-commands-stripped");
    }
  },
);
