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

const notebook = (metadata: unknown) => JSON.stringify({ nbformat: 4, nbformat_minor: 5, metadata, cells: [{ cell_type: "code", execution_count: null, metadata: {}, outputs: [], source: ["for value in range(3):\n", "    print(f\"value is {value}\")"] }] });

test("Python 3 kernel and non-string language metadata render as Python", WEB, async ({ t3, app, screen, browser }) => {
  const kernel = { name: "python3", display_name: "Python 3" };
  const project = await t3.project("Notebook examples", {
    "with-language-info.ipynb": notebook({ kernelspec: kernel, language_info: { name: "python" } }),
    "kernel-only.ipynb": notebook({ kernelspec: kernel }),
    "object-language.ipynb": notebook({ kernelspec: { ...kernel, language: "python" }, language_info: { name: { codemirror_mode: "python" } } }),
  });
  const thread = await t3.thread({ project, title: "Notebook previews", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: true }).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  const labels: string[] = [];
  for (const name of ["with-language-info", "kernel-only", "object-language"]) {
    await screen.getByRole("treeitem", `${name}.ipynb`, { exact: true }).tap();
    await screen.getByText("Saved outputs only. Code is never executed.", { exact: true }).waitFor({ timeout: 120000 });
    await screen.getByRole("region", "Cell 1", { exact: true }).waitFor();
    // The source view's highlighted tokens live in its shadow root.
    await expect.poll(() => browser.evaluate(() => {
      const cell = document.querySelector('section[aria-label="Cell 1"]');
      const text = (node: Element): string => [node.textContent ?? "", ...Array.from(node.querySelectorAll("*")).filter(x => x.shadowRoot).map(x => x.shadowRoot!.textContent ?? "")].join(" ");
      return cell ? text(cell).includes("value is") : false;
    }), { timeout: 120000 }).toBe(true);
    await app.screenshot(name);
    labels.push(await browser.evaluate(() => document.querySelector('section[aria-label="Cell 1"] > div')?.textContent ?? ""));
  }
  await expect(labels).toEqual(["python · 1", "python · 1", "python · 1"]);
});
