import { randomUUID } from "node:crypto";
import { setTimeout } from "node:timers/promises";
import { writeFile, access, readFile } from "node:fs/promises";
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("Deleting an active thread preserves an archived thread's shared worktree", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("shared-worktree");
  const start = (model: string) => runPromise(makeState(T3_HOME).cli([
    "thread", "start", project, "Start", "--title", "Archived owner", "--worktree", "main",
    "--provider", "devReplay", "--model", model, "--wait", "--json",
  ]));
  const started = await start("default").catch((error: unknown) => {
    if (!String(error).includes("not advertised")) throw error;
    return start("showcase");
  });
  const owner = JSON.parse(started.stdout).threadId;
  const { active, worktree } = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const { thread } = yield* client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(owner) });
    if (!thread.worktreePath) throw new Error("Missing worktree");
    const active = yield* client["orchestration.launchThread"]({
      commandId: CommandId.make(randomUUID()), projectId: thread.projectId,
      title: "Active thread", modelSelection: thread.modelSelection,
      runtimeMode: thread.runtimeMode, interactionMode: thread.interactionMode,
      workspaceStrategy: { type: "existing_worktree", worktreePath: thread.worktreePath },
    });
    yield* client["orchestration.dispatchCommand"]({ type: "thread.archive", commandId: CommandId.make(randomUUID()), threadId: thread.id });
    return { active, worktree: thread.worktreePath };
  }).pipe(Effect.scoped));
  const notes = `${worktree}/uncommitted-notes.txt`;
  await writeFile(notes, "Uncommitted notes belonging to Archived owner.\n");
  await t3.open(active);
  await screen.getByRole("button", "Thread actions for Active thread").tap();
  await screen.getByRole("menuitem", "Delete", { exact: true }).tap();
  const dialog = screen.getByRole("alertdialog");
  await dialog.getByRole("button", "Confirm", { exact: true }).tap();
  const prompt = screen.getByText("Delete the worktree too?", { exact: false });
  await expect.poll(async () => (await prompt.isVisible()) || (await dialog.count()) === 0).toBe(true);
  const offered = await prompt.isVisible();
  // Let the dialog transition finish and verify the evidence frame is stable.
  await setTimeout(800);
  let previous = await app.screenshot("shared-worktree-after-thread-delete");
  let stable = false;
  for (let frame = 0; frame < 10; frame++) {
    await setTimeout(500);
    const current = await app.screenshot("shared-worktree-after-thread-delete");
    stable = (await readFile(previous)).equals(await readFile(current));
    previous = current;
    if (stable) break;
  }
  if (!stable) throw new Error("Evidence frame was not stable");
  if (offered) {
    await dialog.getByRole("button", "Confirm", { exact: true }).tap();
    await expect.poll(async () => access(notes).then(() => false, () => true)).toBe(true);
  }
  expect(offered).toBe(false);
  expect(await access(notes).then(() => true, () => false)).toBe(true);
});
