import { readFile } from "node:fs/promises";
import { test, WEB } from "./t3.ts";

test("Archived links and rejected destinations visual matrix", WEB, async ({ t3, app, screen, browser }) => {
  const capture = async (label: string) => {
    let prior = await app.screenshot(label + "-stability-check");
    for (let attempt = 0; attempt < 12; attempt++) {
      await new Promise((resolve) => setTimeout(resolve, 500));
      const current = await app.screenshot(label);
      if ((await readFile(prior)).equals(await readFile(current))) return;
      prior = current;
    }
    throw new Error("Capture did not stabilize: " + label);
  };
  await browser.addInitScript(() => {
    new MutationObserver(() => {
      if (sessionStorage.getItem("rejectDeleted") && document.body?.innerText.includes("This history will be deleted.")) {
        sessionStorage.setItem("deletedHistoryFlashed", "true");
      }
    }).observe(document, { childList: true, subtree: true, characterData: true });
  });
  const project = await t3.project("Archive demo");
  await t3.thread({ project, title: "Archived conversation", messages: ["Keep this saved conversation."] });
  await t3.thread({ project, title: "Disposable conversation", messages: ["This history will be deleted."] });
  await t3.thread({ project, title: "Active conversation", messages: ["Leave this thread active."] });
  await t3.open();
  await screen.getByRole("button", /^Disposable conversation,/).tap({ timeout: 120_000 });
  await screen.getByText("This history will be deleted.", { exact: true }).waitFor();
  const deletedUrl = await browser.url();
  await capture("disposable-before-delete");
  await screen.getByRole("button", /^Disposable conversation,/).secondaryTap();
  await screen.getByText("Delete", { exact: true }).tap();
  await screen.getByRole("button", "Confirm", { exact: true }).tap();
  await screen.getByRole("button", /^Disposable conversation,/).waitFor({ state: "hidden" });
  await browser.evaluate(() => sessionStorage.setItem("rejectDeleted", "true"));
  await browser.goto(deletedUrl);
  await screen.getByRole("heading", "New thread", { exact: true }).waitFor({ timeout: 120_000 });
  await capture("deleted-url");
  const flashed = await browser.evaluate(() => sessionStorage.getItem("deletedHistoryFlashed") === "true");
  if (flashed) throw new Error("Deleted history became visible after confirmed deletion");
  const missingUrl = deletedUrl.replace(/[^/]+$/, "missing-synthetic-thread");
  await browser.goto(missingUrl);
  await screen.getByRole("heading", "New thread", { exact: true }).waitFor({ timeout: 120_000 });
  await capture("missing-url");
  await screen.getByRole("button", /^Archived conversation,/).tap();
  await screen.getByText("Keep this saved conversation.", { exact: true }).waitFor();
  const savedUrl = await browser.url();
  await browser.evaluate(async () => {
    const { appAtomRegistry } = await import("/src/rpc/atomRegistry.ts");
    const { orchestrationEnvironment } = await import("/src/state/orchestration.ts");
    const { threadEnvironment } = await import("/src/state/threads.ts");
    const { readPrimaryEnvironmentId } = await import("/src/state/environments.ts");
    const environmentId = readPrimaryEnvironmentId();
    const threadId = decodeURIComponent(location.pathname.split("/").at(-1)!);
    const fork = await orchestrationEnvironment.v2.dispatchCommand.run(appAtomRegistry, { environmentId, input: {
      type: "thread.fork", commandId: crypto.randomUUID(), sourceThreadId: threadId, targetThreadId: "related-synthetic-thread",
      sourcePoint: { type: "latest_stable" }, title: "Related conversation", createdBy: "user", creationSource: "web"
    } });
    if (fork._tag === "Failure") throw new Error("Could not create related conversation");
    const link = await threadEnvironment.linkPullRequest.run(appAtomRegistry, { environmentId, input: {
      threadId, host: "github.com", repository: "pingdotgg/t3code", number: 23278,
      url: "https://github.com/pingdotgg/t3code/pull/23278", source: "manual"
    } });
    if (link._tag === "Failure") throw new Error("Could not link pull request");
  });
  await screen.getByRole("button", /^Related conversation,/).waitFor();
  await screen.getByRole("button", /^Archived conversation,/).secondaryTap();
  await screen.getByText("Archive thread", { exact: true }).tap();
  await screen.getByRole("button", /^Archived conversation,/).waitFor({ state: "hidden" });
  await screen.getByRole("button", /^Related conversation,/).tap();
  await screen.getByRole("region", "Thread details").getByText("Archived conversation", { exact: true }).waitFor();
  await screen.getByRole("region", "Thread details").getByText("Archived conversation", { exact: true }).hover();
  await capture("relationship-source");
  await screen.getByRole("region", "Thread details").getByText("Archived conversation", { exact: true }).tap();
  await screen.getByRole("heading", /^(Archived conversation|New thread)$/).waitFor();
  await capture("relationship-destination");
  await screen.getByRole("button", /^Active conversation,/).tap();
  await browser.evaluate(async () => {
    const { appAtomRegistry } = await import("/src/rpc/atomRegistry.ts");
    const { pullRequestEnvironment } = await import("/src/state/pullRequests.ts");
    const { readPrimaryEnvironmentId } = await import("/src/state/environments.ts");
    const { readProjects } = await import("/src/state/entities.ts");
    const { openCommandPalette } = await import("/src/commandPaletteBus.ts");
    const environmentId = readPrimaryEnvironmentId();
    const atom = pullRequestEnvironment.linkedThreads({ environmentId, input: {
      projectId: readProjects()[0]!.id, repository: "pingdotgg/t3code", host: "github.com", number: 23278
    } });
    const result = await new Promise<any>((resolve) => {
      const off = appAtomRegistry.subscribe(atom, (value) => {
        if (value._tag === "Success" && !value.waiting) { off(); resolve(value); }
      });
      const value = appAtomRegistry.get(atom);
      if (value._tag === "Success" && !value.waiting) { off(); resolve(value); }
    });
    if (result._tag !== "Success") throw new Error("Could not load PR-linked threads");
    openCommandPalette({ query: "https://github.com/pingdotgg/t3code/pull/23278", linkedThreads: { environmentId, threads: result.value.threads } });
  });
  await screen.getByRole("option", /Archived conversation/).waitFor();
  await capture("pr-linked-thread-list");
  await screen.getByRole("option", /Archived conversation/).tap();
  await screen.getByRole("heading", /^(Archived conversation|New thread)$/).waitFor();
  await capture("pr-linked-destination");
  await browser.goto(savedUrl);
  await screen.getByRole("heading", /^(Archived conversation|New thread)$/).waitFor({ timeout: 120_000 });
  await capture("url-destination");
  if (await browser.evaluate(() => document.body.innerText.includes("Keep this saved conversation."))) {
    await screen.getByRole("region", "Version Control").getByRole("combobox").tap();
    await screen.getByRole("option", /^main/).waitFor();
    await capture("archived-branch-selector");
  }
});
