import { readFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
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("Restoring a removed managed worktree reruns synchronous setup", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("setup-demo");
  const cli = (args: string[]) => runPromise(makeState(T3_HOME).cli(args));
  const token = (await cli(["auth", "session", "issue", "--token-only"])).stdout.trim();
  const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
  const snapshot = await (await fetch(`${app.baseUrl}/api/projects`, { headers })).json();
  const projectId = snapshot.projects.find((p: { workspaceRoot: string }) => p.workspaceRoot === project).id;
  const configured = await fetch(`${app.baseUrl}/api/projects/mutate`, { method: "POST", headers, body: JSON.stringify({
    type: "project.update", commandId: randomUUID(), projectId,
    scripts: [{ id: "setup", name: "Prepare worktree", command: "echo ready > setup-ready.txt", icon: "configure", runOnWorktreeCreate: true, async: false }],
  }) });
  if (!configured.ok) throw new Error(await configured.text());
  const started = await cli(["thread", "start", project, "Initialize this worktree", "--title", "Restore worktree setup", "--worktree", "main", "--branch", "setup-restore", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]);
  const thread = JSON.parse(started.stdout);
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  const listing = (await git("worktree", "list", "--porcelain")).stdout;
  const worktree = listing.split("\n").filter((line: string) => line.startsWith("worktree ")).map((line: string) => line.slice(9)).find((path: string) => path !== project)!;
  if ((await readFile(`${worktree}/setup-ready.txt`, "utf8")) !== "ready\n") throw new Error("Initial setup did not create the marker");
  await t3.open(thread);
  await git("worktree", "remove", "--force", worktree);
  await screen.getByRole("textbox").fill("Read setup-ready.txt after restoring this worktree.");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("Read setup-ready.txt after restoring this worktree.", { exact: true }).first().waitFor();
  await screen.getByRole("button", "Stop generation").waitFor({ state: "visible", timeout: 60_000 });
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 60_000 });
  const marker = await readFile(`${worktree}/setup-ready.txt`, "utf8").catch(() => "MISSING");
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await terminal.focus();
  await browser.keyboard.type("PS1='$ '; clear; printf 'Restored worktree setup check\\n'; cat setup-ready.txt 2>/dev/null || echo 'setup-ready.txt: MISSING'");
  await browser.keyboard.press("Enter");
  await cli(["thread", "show", thread.threadId, "--json"]);
  await app.screenshot("restored-worktree-setup");
  expect(marker, "Restoration must rerun setup before the next provider turn completes").toBe("ready\n");
});
