// @effect-diagnostics nodeBuiltinImport:off -- The scenario stages a local ACP executable.
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 ACP = `
import { createInterface } from "node:readline";

const ids = Array.from({ length: 3 }, (_, index) => "sample-conversation-session-" + index);
const nextCursor = "";
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
for await (const line of createInterface({ input: process.stdin })) {
  const { id, method, params } = JSON.parse(line);
  if (id === undefined) continue;
  if (method === "initialize") {
    send({ id, result: {
      protocolVersion: 1,
      agentCapabilities: { loadSession: true, sessionCapabilities: { list: {} } },
      authMethods: [],
    } });
  } else if (method === "session/new") {
    send({ id, result: { sessionId: "probe" } });
  } else if (method === "session/list" && params.cursor === undefined) {
    send({ id, result: {
      nextCursor,
      sessions: ids.map((sessionId, index) => ({
        sessionId,
        cwd: params.cwd,
        title: "Native conversation " + (index + 1),
      })),
    } });
  } else if (method === "session/list" && params.cursor === nextCursor) {
    send({ id, result: {
      sessions: [{ sessionId: "archived", cwd: params.cwd, title: "Older conversation" }],
    } });
  } else {
    send({ id, error: method === "session/list"
      ? { code: -32602, message: "Invalid session cursor" }
      : { code: -32601, message: "Method not found" },
    });
  }
}
`;

test(
  "Load more stays available when an ACP session page has an empty cursor",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("demo", { "session-agent.mjs": ACP });
    const instanceId = ProviderInstanceId.make("scenario-empty-session-cursor");
    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: "Local Session Agent",
              enabled: true,
              config: {
                source: "local",
                commandPath: process.execPath,
                commandArgs: [NodePath.join(project, "session-agent.mjs")],
              },
            },
          },
        });
      }).pipe(Effect.scoped),
    );

    await t3.open(`/settings/providers?instanceId=${instanceId}`);
    await screen.getByRole("button", "List sessions", { exact: true }).tap({ timeout: 60_000 });
    await screen.getByText("Native conversation 1", { exact: true }).waitFor();
    const more = screen.getByRole("button", "Load more", { exact: true });
    await browser.evaluate(() => {
      const row = Array.from(document.querySelectorAll("*")).find((el) => el.textContent === "Native conversation 3");
      row?.scrollIntoView({ block: "center", behavior: "instant" });
      return null;
    });
    await app.screenshot("first-native-session-page");
    expect(await more.isVisible()).toBe(true);
    await more.tap();
    await screen.getByText("Older conversation", { exact: true }).waitFor();
    await browser.evaluate(() => {
      const row = Array.from(document.querySelectorAll("*")).find((el) => el.textContent === "Older conversation");
      row?.scrollIntoView({ block: "center", behavior: "instant" });
      return null;
    });
    await app.screenshot("older-conversation-loaded");
  },
);
