import { expect } from "e2e";
import { mkdtemp, cp, rm, readFile, writeFile, utimes } from "node:fs/promises";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";

test("Reloading a non-Git project without a rewind on current main", WEB, async ({ t3, app, screen, browser }) => {
  const stableScreenshot = async (label: string) => {
    let previous = await app.screenshot(`${label}-settling`);
    for (let attempt = 0; attempt < 10; attempt++) {
      await new Promise((resolve) => setTimeout(resolve, 500));
      const current = await app.screenshot(`${label}-check-${attempt}`);
      if ((await readFile(previous)).equals(await readFile(current))) {
        await app.screenshot(label);
        return;
      }
      previous = current;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  const original = await t3.project("Notes", { "notes.txt": "Keep these file contents.\n" });
  const parent = await mkdtemp(`${process.env.T3_EVIDENCE_DIR ?? "/tmp"}/notes-`);
  const project = `${parent}/Notes`;
  await cp(original, project, { recursive: true });
  await rm(`${project}/.git`, { recursive: true });
  const { cli } = makeState(T3_HOME);
  await runPromise(cli(["project", "remove", original, "--force"]));
  await runPromise(cli(["project", "add", project, "--title", "Notes"]));
  await writeFile(`${project}/notes.txt`, "Keep these file contents.\nAn unsaved-to-Git edit.\n");
  try {
  await t3.open();
  await screen.getByRole("button", "Showcase", { exact: true }).tap();
  await screen.getByRole("option", "Multi turn", { exact: false }).tap();
  await browser.keyboard.press("Escape");
  await screen.getByTestId("composer-editor").fill("Summarize these notes");
  await screen.getByTestId("composer-editor").press("Enter");
  await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible();
  await expect(screen.getByRole("button", "Stop generation")).toBeHidden();
  await screen.getByTestId("composer-editor").fill("Suggest a follow-up");
  await screen.getByTestId("composer-editor").press("Enter");
  await expect(screen.getByText("second fixture turn complete", { exact: false })).toBeVisible();
  await expect(screen.getByRole("button", "Stop generation")).toBeHidden();
  await expect(screen.getByText("Working", { exact: true })).toBeHidden();
  await screen.getByRole("region", "Conversation", { exact: true }).getByText("Summarize these notes", { exact: true }).hover();
  await stableScreenshot("completed-prompt");
  await browser.reload();
  await screen.getByRole("region", "Conversation", { exact: true }).getByText("Summarize these notes", { exact: true }).hover();
  await stableScreenshot("after-plain-reload");
  } finally {
    await runPromise(cli(["project", "add", original, "--title", "Fixture setup"]));
  }
});
