/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("A slow response fork keeps the chat selected meanwhile", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo-project");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter(event => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some(p => p.instanceId === "devReplay" && p.models?.some(m => m.slug === "showcase"));
      }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const source = await t3.thread({ project, title: "source chat", messages: ["Source message"], model: "showcase" });
  const other = await t3.thread({ project, title: "other chat", messages: ["Other message"], model: "showcase" });
  const control = await t3.thread({ project, title: "control chat", messages: ["Control message"], model: "showcase" });
  await browser.addInitScript(() => {
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function (data) {
      if (typeof data !== "string") return send.call(this, data);
      const parsed = JSON.parse(data);
      const messages = [parsed].flat();
      const isFork = (m: { payload?: { type?: string } }) => m?.payload?.type === "thread.fork";
      if (!messages.some(isFork)) return send.call(this, data);
      const rest = messages.filter(m => !isFork(m));
      if (rest.length) send.call(this, JSON.stringify(rest));
      document.documentElement.dataset.forkHeld = "yes";
      setTimeout(() => {
        send.call(this, Array.isArray(parsed) ? JSON.stringify(messages.filter(isFork)) : data);
        document.documentElement.dataset.forkReleased = "yes";
      }, 8000);
    };
  });
  await t3.open(control);
  await screen.getByRole("button", "Fork from this response").first().tap();
  await browser.mouse.move(970, 600);
  await screen.getByRole("textbox", "Message control chat fork", { exact: true }).waitFor();
  await app.screenshot("staying-in-source-opens-fork-control");
  await t3.open(source);
  await screen.getByRole("button", "Fork from this response").first().tap();
  await browser.locator('html[data-fork-held="yes"]').waitFor();
  await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 1000)); return null; });
  await screen.getByRole("button", /^other chat, /).tap();
  await browser.mouse.move(970, 600);
  await screen.getByText("Other message", { exact: true }).waitFor();
  await app.screenshot("selected-chat-before-fork-lands");
  await browser.locator('html[data-fork-released="yes"]').waitFor();
  await screen.getByRole("button", /^source chat fork, /).waitFor();
  await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 1000)); return null; });
  await app.screenshot("selected-chat-after-fork-lands");
  expect(await browser.evaluate(() => decodeURIComponent(location.pathname))).toContain(other.threadId);
});
