/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Saved notebook tabs and repeated prefix erases preserve terminal columns", WEB, async ({ t3, app, screen, browser }) => {
  const cases = [
    { name: "Tab then cursor erase", text: "Step\twaiting\u001b[9G\u001b[Kdone", expected: "Step    done" },
    { name: "Carriage return then tab", text: "12345678waiting\r\t\u001b[Kdone", expected: "12345678done" },
    { name: "Overwrite across tab", text: "a\tbc\rXYZW", expected: "XYZW    bc" },
    { name: "Repeated prefix erases", text: "x".repeat(160) + "\u001b[1K".repeat(60) + "\rdone", expected: "done" + " ".repeat(156) },
  ];
  const notebook = { nbformat: 4, nbformat_minor: 5, metadata: { language_info: { name: "python" } }, cells: cases.map((item, index) => ({ id: `case-${index}`, cell_type: "code", source: [], metadata: {}, execution_count: index + 1, outputs: [{ output_type: "stream", name: "stdout", text: item.text }] })) };
  const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter(event => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some(provider => provider.instanceId === "devReplay" && provider.models?.some(model => model.slug === "multi-turn"));
      }), Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({ project, title: "Saved notebook outputs", messages: ["Inspect the saved notebook outputs."] });
  await t3.open(thread);
  await screen.getByTestId("composer-editor").waitFor();
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("results.ipynb");
  await screen.getByRole("option", "results.ipynb", { exact: false }).tap();
  await screen.getByText("Saved outputs only", { exact: false }).waitFor();
  await browser.evaluate(() => { (document.activeElement as HTMLElement)?.blur(); });
  await browser.mouse.move(1, 1);
  await app.screenshot("saved-notebook-four-cases");
  const outputs = await browser.evaluate(() => [...document.querySelectorAll("pre")].map(el => el.textContent).filter(text => text && !text.startsWith("#")));
  expect(outputs).toEqual(cases.map(item => item.expected));
});
