/// <reference lib="dom" />
// @effect-diagnostics nodeBuiltinImport:off -- The scenario launches a local ACP fixture.
import * as NodePath from "node:path";

import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";

import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const SESSION_TITLE = "Native session to recover";
const ACP = `
import { createInterface } from "node:readline";

createInterface({ input: process.stdin }).on("line", (line) => {
  const { id, method, params } = JSON.parse(line);
  if (id === undefined) return;
  const results = {
    initialize: {
      protocolVersion: 1,
      agentInfo: { name: "session-scenario", version: "1.0.0" },
      agentCapabilities: { loadSession: true, sessionCapabilities: { list: {}, delete: {} } },
      authMethods: [],
    },
    "session/new": { sessionId: "health-probe" },
    "session/list": {
      sessions: [{ sessionId: "native-draft", cwd: params?.cwd, title: ${JSON.stringify(SESSION_TITLE)} }],
    },
    "session/delete": {},
  };
  const error = method === "session/load"
    ? { code: -32603, message: "Native history is temporarily unavailable" }
    : { code: -32601, message: "Method not found" };
  const result = results[method];
  process.stdout.write(JSON.stringify({
    jsonrpc: "2.0", id, ...(result === undefined ? { error } : { result }),
  }) + "\\n");
});
`;

test(
  "A failed import preserves ownership when an earlier real list response arrives late",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const instanceId = ProviderInstanceId.make("scenario-failed-import-agent");
    const project = await t3.project("demo", { "session-agent.mjs": ACP });
    await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
        yield* client["server.updateSettings"]({
          patch: {},
          providerInstanceMutation: {
            operation: "upsert",
            instanceId,
            instance: {
              driver: ProviderDriverKind.make("acpRegistry"),
              displayName: "Session scenario agent",
              enabled: true,
              config: {
                source: "local",
                commandPath: process.execPath,
                commandArgs: [NodePath.join(project, "session-agent.mjs")],
              },
            },
          },
        });
      }).pipe(Effect.scoped),
    );

    await browser.addInitScript(() => {
      const NativeWebSocket = window.WebSocket;
      const held: Array<{ socket: WebSocket; data: string }> = [];
      const pending = new Set<string>();
      let armed = false;
      let releasing = false;
      Object.assign(window, {
        scenarioArmList: () => { armed = true; },
        scenarioReleaseList: () => {
          releasing = true;
          for (const { socket, data } of held.splice(0)) {
            socket.dispatchEvent(new MessageEvent("message", { data }));
          }
          releasing = false;
          document.documentElement.dataset.scenarioReleased = "yes";
        },
      });
      window.WebSocket = class extends NativeWebSocket {
        constructor(url: string | URL, protocols?: string | string[]) {
          super(url, protocols);
          this.addEventListener("message", (event) => {
            if (releasing || typeof event.data !== "string") return;
            const messages = [JSON.parse(event.data)].flat();
            if (messages.some((response) => response?._tag === "Exit" && pending.delete(String(response.requestId)))) {
              event.stopImmediatePropagation();
              held.push({ socket: this, data: event.data });
              document.documentElement.dataset.scenarioHeld = "yes";
            }
          });
        }
        override send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {
          if (armed && typeof data === "string") {
            for (const request of [JSON.parse(data)].flat()) {
              if (request?.tag === "server.listAcpRegistrySessions") {
                pending.add(String(request.id));
                armed = false;
              }
            }
          }
          super.send(data);
        }
      };
    });
    await t3.open(`/settings/providers?instanceId=${instanceId}`);
    await screen.getByRole("button", "List sessions", { exact: true }).tap({ timeout: 60_000 });
    await screen.getByText(SESSION_TITLE, { exact: true }).waitFor();
    const remove = screen.getByRole("button", "Delete", { exact: true });
    expect(await remove.isEnabled()).toBe(true);
    await browser.evaluate(() => { (window as any).scenarioArmList(); return null; });
    await screen.getByRole("button", "Refresh", { exact: true }).tap();
    await browser.locator('html[data-scenario-held="yes"]').waitFor({ state: "attached" });
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => {})));
      return null;
    });
    await app.screenshot("stale-list-held-before-import");
    await screen.getByRole("button", "Import", { exact: true }).tap();
    await screen
      .getByText("Could not import the ACP session history.", { exact: true })
      .waitFor({ timeout: 60_000 });

    await remove.waitFor();
    await screen.getByRole("button", "Import", { exact: true }).waitFor();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => {})));
      return null;
    });
    await app.screenshot("owned-while-stale-list-held");
    const deletableBeforeRelease = await remove.isEnabled();
    await browser.evaluate(() => { (window as any).scenarioReleaseList(); return null; });
    await screen.getByRole("button", "Loading", { exact: true }).waitFor({ state: "hidden" });
    await screen.getByRole("button", "Refresh", { exact: true }).waitFor();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => {})));
      return null;
    });
    await app.screenshot("ownership-after-stale-list-arrives");
    expect({
      deletableBeforeRelease,
      deletableAfterRelease: await remove.isEnabled(),
      importAvailable: await screen.getByRole("button", "Import", { exact: true }).isEnabled(),
    }).toEqual({ deletableBeforeRelease: false, deletableAfterRelease: false, importAvailable: true });
  },
);
