import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Cleanup removes a clean detached worktree reachable from main", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Cleanup-demo", { "tracked.txt": "Committed on main\n" });
  const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
  const origin = `${project}-origin.git`;
  git(project, "init", "--bare", origin);
  git(project, "remote", "add", "origin", origin);
  git(project, "push", "-u", "origin", "main");
  git(project, "remote", "set-head", "origin", "main");
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, "Finish this sample turn", "--title", "Detached cleanup example", "--provider", "devReplay", "--model", "multi-turn", "--worktree", "origin/main", "--branch", "cleanup-example", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout);
  const listing = git(project, "worktree", "list", "--porcelain");
  const worktree = listing.split("\n\n").find((block) => block.includes("refs/heads/cleanup-example"))!.split("\n")[0]!.slice(9);
  git(worktree, "switch", "--detach", "origin/main");
  if (git(worktree, "status", "--porcelain") !== "") throw new Error("Fixture checkout is not clean");
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).first().waitFor({ timeout: 120_000 });
  await browser.keyboard.press("Control+k");
  await screen.getByRole("dialog", "Command palette").getByRole("combobox").fill("Restart agent session");
  await screen.getByText("Restart agent session", { exact: true }).tap();
  await screen.getByRole("button", "Settle thread").first().press("Enter");
  // Cleanup intentionally gives settlement scripts sixty seconds to finish.
  await new Promise((resolve) => setTimeout(resolve, 65_000));
  await t3.open("/settings/worktrees");
  await screen.getByRole("button", "Advanced", { exact: true }).last().tap();
  await screen.getByRole("switch", "Delete unchanged worktrees").tap();
  await t3.open("/settings/maintenance");
  // Hide synthetic filesystem locations in public evidence; cleanup reasons remain visible.
  await browser.evaluate(() => { const style = document.createElement("style"); style.textContent = "#storage-cleanup-last-run code { visibility: hidden; }"; document.head.append(style); });
  await screen.getByRole("button", /Last run/).tap();
  await screen.getByText("Machine", { exact: true }).waitFor();
  await new Promise((resolve) => setTimeout(resolve, 1_000));
  await app.screenshot("configured-cleanup-result");
  await screen.getByRole("button", "Delete now", { exact: true }).tap();
  if (!existsSync(worktree)) {
    await screen.getByText("Scenario: Nothing needed cleanup.", { exact: true }).waitFor();
  } else {
    await screen.getByText("Machine", { exact: true }).waitFor();
  }
  await new Promise((resolve) => setTimeout(resolve, 1_000));
  await app.screenshot("manual-cleanup-result");
  await expect(existsSync(worktree)).toBe(false);
});
