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

const notebook = {
  nbformat: 4, nbformat_minor: 5,
  metadata: { language_info: { name: "python" } },
  cells: [{ id: "progress", cell_type: "code", metadata: {}, execution_count: 1,
    source: ["from tqdm import tqdm\n", "for _ in tqdm(range(10)): pass\n", "print(\"done\")"],
    outputs: [{ output_type: "stream", name: "stderr", text: ["\r 10%|#         |", "\r100%|##########|\n", "done\r\n"] }],
  }],
};

test("Notebook progress updates show only the last frame and preserve subsequent lines", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("notebook-demo", { "progress.ipynb": JSON.stringify(notebook) });
  const thread = await t3.thread({ project, title: "Review notebook progress", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1080 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "progress.ipynb").tap();
  await screen.getByText("Saved outputs only. Code is never executed.").waitFor();
  const output = 'section[aria-label="Cell 1"] pre.whitespace-pre-wrap';
  await browser.locator(output).waitFor();
  await screen.getByText("Loading code…").waitFor({ state: "hidden" });
  await screen.getByText("tqdm", { exact: true }).first().waitFor();
  await app.screenshot("notebook-progress-output");
  await expect.poll(() => browser.evaluate((selector) => document.querySelector(selector)?.textContent, output)).toBe("100%|##########|\ndone\n");
});
