import { mkdir, writeFile, access } 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("Cleanup removes a deleted thread's bare-repository worktree", WEB, async ({t3, app, browser, screen}) => {
  const seed = await t3.project("seed");
  const bareproj = `${T3_HOME}/workspaces/bareproj`;
  await mkdir(bareproj, {recursive:true});
  const git = (...args: string[]) => runPromise(run("git", args, {cwd: bareproj}));
  await git("clone", "--bare", seed, `${bareproj}/.bare`);
  await writeFile(`${bareproj}/.git`, "gitdir: ./.bare\n");
  await git("worktree", "add", "main", "main");
  const state = makeState(T3_HOME);
  const added = await runPromise(state.cli(["project", "add", `${bareproj}/main`]));
  const id = /Added project (\S+) /.exec(added.stdout)?.[1];
  if (!id) throw new Error(added.stdout);
  t3.trackProject(id);
  const started = await runPromise(state.cli(["thread", "start", `${bareproj}/main`, "hello", "--title", "hello", "--provider", "devReplay", "--model", "showcase", "--worktree", "main", "--branch", "t3/bare-repro", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout);
  const before = (await git("--git-dir=.bare", "worktree", "list", "--porcelain")).stdout;
  const worktree = before.split("\n\n").find(x=>x.includes("branch refs/heads/t3/bare-repro"))?.split("\n")[0]?.slice(9);
  if (!worktree) throw new Error("T3 worktree missing before deletion");
  await t3.open("/settings/worktrees");
  await screen.getByRole("switch", "Delete worktrees with deleted threads", {exact:true}).tap();
  await screen.getByRole("switch", "Delete worktrees with deleted threads", {exact:true}).waitFor();
  await t3.open(thread);
  await browser.locator('[data-thread-item]').filter({has:screen.getByText("hello",{exact:true})}).waitFor();
  await browser.evaluate(() => {
    const row = [...document.querySelectorAll('[data-sidebar-row]')].find(x=>x.textContent?.includes("hello"));
    if (!row) throw new Error("Missing thread row");
    row.dispatchEvent(new MouseEvent("contextmenu", {bubbles:true,cancelable:true,button:2}));
    return null;
  });
  await screen.getByRole("menuitem", "Delete", {exact:true}).tap();
  await screen.getByRole("button", "Confirm", {exact:true}).tap();
  await browser.locator('[data-thread-item]').filter({has:screen.getByText("hello",{exact:true})}).waitFor({state:"hidden"});
  await t3.open("/settings/maintenance");
  const sweep = screen.getByRole("button", "Delete now", {exact:true});
  await sweep.tap();
  await screen.getByRole("button", "Deleting…", {exact:true}).waitFor({state:"hidden"});
  await screen.getByRole("button", /^Last run/).waitFor();
  try {
    await expect(screen.getByText(/item couldn't be removed/)).not.toBeVisible();
    await expect.poll(async () => {try {await access(worktree); return true;} catch {return false;}}).toBe(false);
    await expect.poll(async () => (await git("--git-dir=.bare", "worktree", "list", "--porcelain")).stdout.includes(worktree)).toBe(false);
  } finally {
    await app.screenshot("bare-repository-cleanup-result");
  }
});
