/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
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";

test("Loaded linked history survives a fresh subscription to the same snapshot", WEB, async ({ t3, app, screen, browser }) => {
  const local = await t3.project("reader");
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    const remoteState = makeState(SECOND_HOME).state;
    const remote = await remoteState.project("archive");
    const thread = await remoteState.thread({ project: remote, title: "Archive conversation", messages: Array.from({length: 42}, (_, i) => `Archive note ${String(i + 1).padStart(2, "0")}`) });
    const via = await runPromise(environmentId(app.baseUrl ?? ""));
    const there = await runPromise(environmentId(host));
    await runPromise(Effect.gen(function* () {
      const a = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      const b = yield* rpcClient(SECOND_HOME, host);
      yield* a["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      yield* b["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      yield* a["peerLinks.link"]({ url: host, pairingCode: token, access: "read-only" });
    }).pipe(Effect.scoped));
    const link = `https://app.t3.codes/${there}/${thread.threadId}`;
    const reader = await t3.thread({ project: local, title: "Read the archive", messages: [`Review this conversation: ${link}`] });
    await browser.addInitScript(() => {
      const Native = window.WebSocket;
      const sockets: WebSocket[] = [];
      window.WebSocket = new Proxy(Native, { construct(Target, args) { const socket = new Target(...args as [string, string[]?]); sockets.push(socket); return socket; } });
      Object.assign(window, { reconnectForEvidence: () => sockets.filter(s => new URL(s.url).pathname === "/ws").forEach(s => s.close(4000, "Resume connection")) });
    });
    await t3.open(`/linked/${via}/${there}/${thread.threadId}`);
    await screen.getByText("Read-only", { exact: true }).waitFor();
    const top = async () => browser.evaluate(() => { for (const element of document.querySelectorAll<HTMLElement>("*")) { if (element.scrollHeight > element.clientHeight + 100 && element.clientHeight > 100) element.scrollTop = 0; } });
    await top();
    await screen.getByRole("button", "Load earlier turns").tap();
    await top();
    await screen.getByRole("button", "Agent Archive note 01").waitFor();
    await top();
    await runPromise(Effect.sleep("500 millis"));
    await app.screenshot("earlier-history-loaded");
    await browser.evaluate(() => (window as any).reconnectForEvidence());
    await runPromise(Effect.sleep("5 seconds"));
    await top();
    await runPromise(Effect.sleep("500 millis"));
    await app.screenshot("history-after-refresh");
    await expect(screen.getByRole("button", "Agent Archive note 01")).toBeVisible();
  } finally { await server.stop(); }
});
