/// <reference lib="dom" />
import * as fs from "node:fs";
import { T3_HOME } from "../e2e.config.ts";
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: ["import sys; sys.stdout.write('Processing…\\r\\x1b[2KDone'); sys.stdout.flush()"],
    outputs: [{ name: "stdout", output_type: "stream", text: ["Processing…\r", "\x1b[2KDone"] }] }],
};

test("Notebook saved output honors erase-entire-line after carriage return", 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 status", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1080 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  const composer = screen.getByRole("textbox");
  await composer.fill("Quote, verbatim, the final status line shown in the output of the code cell in the attached notebook text. Do not open the raw .ipynb file; only use the extracted text you were given.");
  await browser.evaluate((payload) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]');
    if (!input) throw new Error("Attachment input missing");
    const files = new DataTransfer();
    files.items.add(new File([payload], "progress.ipynb", { type: "application/x-ipynb+json" }));
    input.files = files.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, JSON.stringify(notebook));
  await screen.getByRole("button", "File attachment, progress.ipynb", { exact: false }).waitFor();
  await composer.press("Enter");
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("button", "File attachment, progress.ipynb", { exact: false }).tap();
  await browser.locator('section[aria-label="Cell 1"] > div.border-t pre').waitFor({ state: "visible", timeout: 120_000 });
  await browser.locator('section[aria-label="Cell 1"] [data-file]').waitFor({ state: "visible" });
  await app.screenshot("attachment-notebook-status");
  const sidecars = fs.globSync("**/*.ipynb.txt", { cwd: T3_HOME });
  const extracted = sidecars.map(path => fs.readFileSync(`${T3_HOME}/${path}`, "utf8")).join("\n");
  const artifact = `/tmp/factory-pr-45184-evidence-2/extracted-${Date.now()}.txt`;
  fs.writeFileSync(artifact, extracted);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("progress.ipynb");
  await screen.getByRole("option", "progress.ipynb", { exact: false }).tap();
  await browser.locator('section[aria-label="Cell 1"] > div.border-t pre').waitFor({ state: "visible", timeout: 120_000 });
  try {
    await expect.poll(() => browser.evaluate(() => document.querySelector('section[aria-label="Cell 1"] > div.border-t pre')?.textContent?.trim())).toBe("Done");
    expect(extracted).toContain("Output:\nDone");
    expect(extracted).not.toContain("Doneessing…");
  } finally {
    await browser.locator('section[aria-label="Cell 1"] [data-file]').waitFor({ state: "visible" });
    await app.screenshot("notebook-final-status");
  }
});
