import { randomUUID } from "node:crypto";
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Cleanup removes a clean detached worktree whose commit remains on main", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("detached-cleanup", { "README.md": "Synthetic cleanup demonstration\n" });
  const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
  const remote = `${project}-origin.git`;
  git(project, "init", "--bare", remote);
  git(project, "remote", "add", "origin", remote);
  git(project, "push", "-u", "origin", "main");
  git(project, "remote", "set-head", "origin", "main");
  const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "first", "--title", "Clean detached worktree", "--worktree", "main", "--branch", "cleanup-demo", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
  const { threadId: id } = JSON.parse(started.stdout);
  const threadId = ThreadId.make(id);
  const worktree = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const projection = yield* client["orchestration.getThreadProjection"]({ threadId });
    for (const session of projection.providerSessions) {
      yield* client["orchestration.dispatchCommand"]({ type: "provider-session.detach", commandId: CommandId.make(randomUUID()), threadId, providerSessionId: session.id });
    }
    yield* client["orchestration.dispatchCommand"]({ type: "thread.settle", commandId: CommandId.make(randomUUID()), threadId });
    return projection.thread.worktreePath!;
  }).pipe(Effect.scoped));
  git(worktree, "switch", "--detach", "origin/main");
  if (git(worktree, "status", "--porcelain") !== "") throw new Error("Fixture worktree is dirty");
  if (git(worktree, "rev-list", "HEAD", "--not", "--branches", "--remotes") !== "") throw new Error("Fixture has unique commits");
  await t3.open("/settings/worktrees");
  await browser.locator("#storage-worktrees").getByRole("button", "Advanced", { exact: true }).tap();
  await screen.getByRole("switch", "Delete unchanged worktrees", { exact: true }).tap();
  // The real cleanup guard reserves one minute for settle scripts.
  await new Promise(resolve => setTimeout(resolve, 65_000));
  await t3.open("/settings/maintenance");
  // Hide private filesystem paths in the public capture; leave the app's result and thread visible.
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.textContent = '#storage-cleanup-last-run code { visibility: hidden; max-height: 18px; overflow: hidden; }';
    document.head.appendChild(style);
  });
  await screen.getByRole("button", "Delete now", { exact: true }).tap();
  await screen.getByRole("button", "Delete now", { exact: true }).waitFor();
  await screen.getByRole("button", /^Last run/).tap();
  await browser.locator("#storage-cleanup-last-run").waitFor();
  await screen.getByText(/Repository or branch changed|No commits beyond the default branch/).waitFor();
  await browser.locator("#storage-cleanup-last-run").scrollIntoView();
  await app.screenshot("detached-worktree-cleanup-result");
  await expect(browser.locator("#storage-cleanup-last-run")).toContainText("No commits beyond the default branch");
  expect(existsSync(worktree)).toBe(false);
});
