/// <reference lib="dom" />
import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Adjacent saved stdout records keep only the final progress frame", WEB, async ({ t3, app, screen, browser }) => {
  const notebook = JSON.stringify({ nbformat: 4, nbformat_minor: 5, metadata: {}, cells: [{ cell_type: "code", id: "progress", metadata: {}, execution_count: 1, source: ["print('Status: Done')"], outputs: [
    { output_type: "stream", name: "stdout", text: "Status: 10%" },
    { output_type: "stream", name: "stdout", text: "\rStatus: Done\n" }
  ] }] });
  const project = await t3.project("notebook-demo", { "progress.ipynb": notebook });
  const thread = await t3.thread({ project, title: "Notebook saved outputs", messages: ["Start"] });
  await t3.open(thread);
  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", { exact: false }).waitFor({ timeout: 60000 });
  await screen.getByText("Status: Done", { exact: true }).waitFor();
  await screen.getByText("Loading code...", { exact: true }).waitFor({ state: "hidden", timeout: 60000 });
  await app.screenshot("saved-stream-final-frame");
  const stale = await browser.evaluate(() => Array.from(document.querySelectorAll("pre")).some(el => el.textContent?.includes("Status: 10%")));
  await browser.evaluate((content) => {
    const input = document.querySelector<HTMLInputElement>('form[data-chat-composer-form] input[type="file"]');
    if (!input) throw new Error("Composer file input missing");
    const transfer = new DataTransfer();
    transfer.items.add(new File([content], "progress.ipynb", { type: "application/x-ipynb+json" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, notebook);
  const attachments = `${T3_HOME}/userdata/attachments`;
  const sidecars = () => readdirSync(attachments, { recursive: true }).map(String).filter(p => p.endsWith(".txt"));
  await expect.poll(() => sidecars().length).toBe(1);
  const attachmentText = readFileSync(`${attachments}/${sidecars()[0]}`, "utf8");
  const cliText = execFileSync(process.execPath, ["apps/server/src/bin.ts", "__document-text", `${project}/progress.ipynb`, ".ipynb"], { cwd: APP_DIR, encoding: "utf8" });
  const report = `# Fresh notebook extraction\n\n## Attachment upload sidecar\n\n\`\`\`text\n${attachmentText}\n\`\`\`\n\n## Server __document-text\n\n\`\`\`text\n${cliText}\n\`\`\`\n`;
  const outDir = `/tmp/factory-pr-44486-evidence-1/run-${Date.now()}`;
  mkdirSync(outDir);
  writeFileSync(`${outDir}/extraction.md`, report);
  writeFileSync(`${project}/extraction.md`, report);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extraction.md");
  await screen.getByRole("option", "extraction.md", { exact: false }).tap();
  await screen.getByText("Attachment upload sidecar", { exact: false }).waitFor();
  await screen.getByPlaceholder("Search files…").waitFor({ state: "hidden" });
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {}))); });
  await app.screenshot("fresh-extraction");
  expect(stale).toBe(false);
  expect(attachmentText).not.toContain("Status: 10%");
  expect(cliText).not.toContain("Status: 10%");
});
