import { mkdir, readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("A leftover worktree folder does not block a new thread", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("sample-app", { "README.md": "# Sample app\n" });
  const { cli } = makeState(T3_HOME);
  const start = (title: string) => runPromise(cli([
    "thread", "start", project, "Explain this sample app", "--title", title,
    "--worktree", "main", "--branch", "feature/foo", "--provider", "devReplay",
    "--model", "multi-turn", "--wait", "--json",
  ], [0, 1, 2]));
  await start("Original worktree");
  const git = (args: string[]) => runPromise(run("git", args, { cwd: project }));
  const originalList = (await git(["worktree", "list", "--porcelain"])).stdout;
  const original = originalList.split("\n\n").find((entry) => entry.includes("branch refs/heads/feature/foo"))!.split("\n")[0]!.slice(9);
  await git(["worktree", "remove", "--force", original]);
  await git(["branch", "-D", "feature/foo"]);
  await mkdir(original, { recursive: true });
  await writeFile(`${original}/notes.txt`, "Keep these notes intact.\n");
  const second = JSON.parse((await start("Retry with leftover folder")).stdout);
  await t3.open();
  await screen.getByRole("button", "Retry with leftover folder", { exact: false }).tap();
  await screen.getByText(second.status === "completed" ? "first fixture turn complete" : "Workspace preparation failed", { exact: false }).first().waitFor({ state: "visible" });
  await screen.getByText("Syncing messages", { exact: false }).waitFor({ state: "hidden" });
  await app.screenshot("retry-with-leftover-folder");
  expect(second.status).toBe("completed");
  expect(await readFile(`${original}/notes.txt`, "utf8")).toBe("Keep these notes intact.\n");
  const current = (await git(["worktree", "list", "--porcelain"])).stdout;
  const replacement = current.split("\n\n").find((entry) => entry.includes("branch refs/heads/feature/foo"))!.split("\n")[0]!.slice(9);
  expect(replacement === original).toBe(false);
});
