import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

test("Reopening stale workspace Markdown through Files and chat fetches host edits", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Revision demo", { "revision.md": "# Revision A\n\nOriginal host contents.\n" });
  await t3.thread({ project, title: "File reopening", messages: ["Inspect the Markdown file."] });
  const capture = async (label: string) => {
    for (let attempt = 0; attempt < 6; attempt++) {
      const first = await app.screenshot(`${label}-settling-${attempt}`);
      await wait(500);
      const second = await app.screenshot(label);
      if ((await readFile(first)).equals(await readFile(second))) return;
    }
    throw new Error(`The ${label} capture did not settle`);
  };
  await t3.open();
  await screen.getByRole("button", /File reopening.*Revision demo/).tap();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", /^Files/).tap();
  await screen.getByRole("treeitem", "revision.md").tap();
  await screen.getByRole("button", "Show rendered markdown").tap();
  await screen.getByRole("heading", "Revision A").textContent();
  await wait(500);
  await capture("initial-revision-a");
  await screen.getByRole("button", "Revision demo", { exact: true }).tap();
  await writeFile(`${project}/revision.md`, "# Revision B\n\nUpdated on the host after the initial read.\n");
  await wait(38_000);
  await screen.getByRole("treeitem", "README.md").tap();
  await screen.getByRole("treeitem", "revision.md").tap();
  await wait(2000);
  await capture("reopened-files");
  const filesText = await browser.evaluate(() => document.body.innerText);
  await screen.getByRole("button", "Revision demo", { exact: true }).tap();
  await writeFile(`${project}/revision.md`, "# Revision C\n\nUpdated on the host before reopening through the chat link.\n");
  await wait(38_000);
  await screen.getByRole("link", "revision.md").tap();
  await wait(2000);
  await capture("reopened-chat-link");
  const chatText = await browser.evaluate(() => document.body.innerText);
  expect(filesText).toContain("Revision B");
  expect(chatText).toContain("Revision C");
});
