/// <reference lib="dom" />
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const SAME_ID = "import:codex:0199aaaa-bbbb-7ccc-8ddd-eeeeffff0001";
const seedCopy = (home: string, origin: string, workspace: string, title: string) => runPromise(Effect.gen(function* () {
  const client = yield* rpcClient(home, origin);
  const item = yield* client["orchestration.subscribeShell"]({}).pipe(Stream.runHead);
  if (item._tag !== "Some" || item.value.kind !== "snapshot") throw Error("No snapshot");
  const project = item.value.snapshot.projects.find(p => p.workspaceRoot === workspace);
  if (!project) throw Error("No project");
  yield* client["orchestration.dispatchCommand"]({
    type: "thread.create", commandId: CommandId.make(crypto.randomUUID()),
    threadId: ThreadId.make(SAME_ID), projectId: project.id, title,
    modelSelection: { instanceId: "devReplay", model: "multi-turn" },
    runtimeMode: "full-access", interactionMode: "default", branch: null, worktreePath: null,
    createdBy: "user", creationSource: "web",
  });
}).pipe(Effect.scoped));

test("Pasted same-id threads keep both machines through sending and opening", WEB, async ({t3, app, browser, screen}) => {
  const origin = app.baseUrl ?? "";
  const workspace = await t3.project("primary");
  const input = {project: workspace, title: "Compare thread links", messages: ["Ready"]};
  const current = await t3.thread({...input, model: "default"}).catch((error) => {
    if (!String(error).includes("Model default is not advertised")) throw error;
    return t3.thread(input);
  });
  const server = startSecondServer(origin);
  try {
    const {host, token} = await server.ready;
    const otherWorkspace = await makeState(SECOND_HOME).state.project("secondary");
    await seedCopy(T3_HOME, origin, workspace, "Machine A copy");
    await seedCopy(SECOND_HOME, host, otherWorkspace, "Machine B copy");
    await runPromise(Effect.gen(function* () {
      const primary = yield* rpcClient(T3_HOME, origin);
      const secondary = yield* rpcClient(SECOND_HOME, host);
      for (const client of [primary, secondary]) yield* client["server.updateSettings"]({patch: {linkedEnvironmentsEnabled: true}});
      const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]);
      yield* primary["peerLinks.link"]({url: host, pairingCode: JSON.parse(pairing.stdout).credential, access: "approval-required"});
    }).pipe(Effect.scoped));
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "Link from Scenario to Scenario: Supervised, Reachable").waitFor();
    const envA = await runPromise(environmentId(origin));
    const envB = await runPromise(environmentId(host));
    await t3.open(current);
    await screen.getByRole("textbox").tap();
    await browser.evaluate((text) => {
      const editor = document.activeElement;
      if (!(editor instanceof HTMLElement) || !editor.isContentEditable) throw Error("Composer not focused");
      const clipboardData = new DataTransfer();
      clipboardData.setData("text/plain", text);
      editor.dispatchEvent(new ClipboardEvent("paste", {clipboardData, bubbles:true, cancelable:true}));
      return null;
    }, [envA, envB].map(env => `https://app.t3.codes/threads/${env}/${encodeURIComponent(SAME_ID)}`).join("\n"));
    await browser.locator('[role="textbox"] [data-slot="context-chip-label"]').first().waitFor();
    await app.screenshot("pasted-two-machines");
    const pasted = await browser.evaluate(() => [...document.querySelectorAll('[role="textbox"] [data-slot="context-chip-label"]')].map(n => n.textContent));
    await browser.keyboard.press("Enter");
    await browser.locator('a[aria-label^="Thread,"]').first().waitFor({state: "attached"});
    await browser.evaluate(() => { document.querySelector('a[aria-label^="Thread,"]')?.scrollIntoView({block: "center", behavior: "instant"}); return null; });
    await app.screenshot("sent-two-machines");
    const sent = await browser.evaluate(() => [...document.querySelectorAll('a[aria-label^="Thread,"]')].map(n => ({label:n.querySelector('[data-slot="context-chip-label"]')?.textContent, href:n.getAttribute("href")})));
    await browser.locator('a[aria-label^="Thread,"]').first().tap();
    await screen.getByRole("heading", /Machine [AB] copy/).waitFor();
    await screen.getByRole("textbox").waitFor();
    await screen.getByText(/Syncing messages/).waitFor({state: "hidden"});
    await app.screenshot("opened-first-chip");
    const opened = await browser.evaluate(() => location.pathname);
    expect({pasted, sent, opened}).toEqual({
      pasted: ["Machine A copy", "Machine B copy"],
      sent: [{label:"Machine A copy", href:`/${envA}/${encodeURIComponent(SAME_ID)}`}, {label:"Machine B copy", href:`/${envB}/${encodeURIComponent(SAME_ID)}`}],
      opened: `/${envA}/${encodeURIComponent(SAME_ID)}`,
    });
  } finally { await server.stop(); }
});
