/// <reference lib="dom" />
import { CommandId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";

import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const olderTitle = "Older deployment notes";

test(
  "The issue link picker explains why an older thread on another environment cannot be linked",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const primary = app.baseUrl ?? "";
    const localProject = await t3.project("demo");
    await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: localProject }));
    const localProjectId = await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, primary);
        const { projects } = yield* client["orchestration.getArchivedShellSnapshot"]({});
        const id = projects.find((project) => project.workspaceRoot === localProject)?.id;
        if (id === undefined) throw new Error("The issue project was not found.");
        return id;
      }).pipe(Effect.scoped),
    );
    const localEnvironmentId = await runPromise(environmentId(primary));
    const server = startSecondServer(primary);
    try {
      const { host, token } = await server.ready;
      const remoteProject = await makeState(SECOND_HOME).state.project("remote-demo");
      await runPromise(
        Effect.gen(function* () {
          const client = yield* rpcClient(SECOND_HOME, host);
          const { projects } = yield* client["orchestration.getArchivedShellSnapshot"]({});
          const projectId = projects.find((project) => project.workspaceRoot === remoteProject)?.id;
          if (projectId === undefined) throw new Error("The remote project was not found.");
          // Settle the target first so the 25 newer threads push it out of the shell.
          for (let index = 0; index <= 25; index++) {
            const threadId = ThreadId.make(`scenario:remote-thread:${index}`);
            yield* client["orchestration.dispatchCommand"]({
              type: "thread.create",
              commandId: CommandId.make(`scenario:create:${index}`),
              threadId,
              projectId,
              title: index === 0 ? olderTitle : `Recent work ${index}`,
              createdBy: "user",
              creationSource: "web",
              modelSelection: {
                instanceId: ProviderInstanceId.make("devReplay"),
                model: "showcase",
              },
              runtimeMode: "full-access",
              interactionMode: "default",
              branch: null,
              worktreePath: null,
            });
            yield* client["orchestration.dispatchCommand"]({
              type: "thread.settle",
              commandId: CommandId.make(`scenario:settle:${index}`),
              threadId,
            });
          }
          const shell = yield* client["orchestration.subscribeShell"]({
            omitOlderSettled: true,
          }).pipe(
            Stream.filter((event) => event.kind === "snapshot"),
            Stream.runHead,
          );
          if (
            Option.isNone(shell) ||
            !shell.value.snapshot.olderSettled?.counts.some(
              (entry) => entry.projectId === projectId,
            ) ||
            shell.value.snapshot.threads.some((thread) => thread.title === olderTitle)
          ) {
            throw new Error("The remote shell must omit the older thread.");
          }
        }).pipe(Effect.scoped),
      );

      
      await t3.open("/settings/connections");
      await screen.getByRole("button", "List", { exact: true }).tap();
      await screen.getByRole("button", "Add environment").tap();
      const pairing = screen.getByRole("dialog");
      await pairing.getByPlaceholder("backend.example.com").fill(host);
      await pairing.getByPlaceholder("PAIRCODE").fill(token);
      await pairing.getByRole("button", "Add environment").tap();
      await screen.getByRole("button", "More actions for Scenario").waitFor({ timeout: 60_000 });

      await t3.open(
        `/issues?selectedEnvironmentId=${localEnvironmentId}&selectedProjectId=${localProjectId}&tracker=github&scope=pingdotgg/t3code&key=48391`,
      );
      await screen.getByRole("button", "Link to thread", { exact: true }).waitFor();
      await browser.evaluate((remoteHost) => {
        const send = WebSocket.prototype.send;
        WebSocket.prototype.send = function(data) {
          const request = typeof data === "string" ? JSON.parse(data) : null;
          if (this.url.startsWith(remoteHost.replace("http", "ws")) &&
              request?._tag === "Request" && request.tag === "orchestration.searchThreads") {
            document.documentElement.dataset.remoteSearch = "held";
            document.addEventListener("release-remote-search", () => send.call(this, data), { once: true });
            return;
          }
          return send.call(this, data);
        };
        return null;
      }, host);
      await screen.getByRole("button", "Link to thread", { exact: true }).tap();
      const picker = screen.getByRole("dialog", "Link issue to a thread");
      await picker.getByPlaceholder("Search threads or projects...").fill(olderTitle);
      await browser.locator("html[data-remote-search=held]").waitFor({ state: "attached" });
      // Observe the local answer while the real remote request remains in flight.
      await browser.evaluate(() => new Promise((resolve) => setTimeout(() => resolve(null), 1500)));
      await app.screenshot("remote-search-pending");
      const pendingStatus = await picker.getByRole("status").textContent();
      await browser.evaluate(() => {
        document.dispatchEvent(new Event("release-remote-search"));
        return null;
      });
      await picker.getByText(/Threads on other environments can't be linked here/).waitFor();
      await app.screenshot("remote-search-complete");
      expect(pendingStatus).toBe("Searching…");

    } finally {
      await server.stop();
    }
  },
);
