// @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 session = (number, cwd) => ({
  sessionId: "native-" + number,
  cwd,
  title: "Native conversation " + number,
});
for await (const line of createInterface({ input: process.stdin })) {
  const { id, method, params } = JSON.parse(line);
  if (id === undefined) continue;
  const result =
    method === "initialize" ? {
      protocolVersion: 1,
      agentCapabilities: { loadSession: true, sessionCapabilities: { list: {} } },
      authMethods: [],
    } :
    method === "session/new" ? { sessionId: "health-probe" } :
    method === "session/list" ? (
      params.cursor === "older"
        ? { sessions: [session(258, params.cwd)] }
        : {
            sessions: Array.from({ length: 257 }, (_, index) => session(index + 1, params.cwd)),
            nextCursor: "older",
          }
    ) :
    undefined;
  const response = result === undefined
    ? { id, error: { code: -32601, message: "Method not found" } }
    : { id, result };
  process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...response }) + "\\n");
}
`;

test(
  "Native ACP conversations remain available when an agent returns a large page",
  WEB,
  async ({ t3, app, screen }) => {
    const project = await t3.project("demo", { "session-agent.mjs": ACP });
    const instanceId = ProviderInstanceId.make("scenario-large-session-page");
    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 });
    const more = screen.getByRole("button", "Load more", { exact: true });
    const loading = screen.getByRole("button", "Loading", { exact: true });
    await more.tap();
    await loading.waitFor({ state: "hidden" });
    if (await more.isVisible()) await more.tap();
    await screen.getByText("Native conversation 258", { exact: true }).waitFor();

    const missingConversation = screen.getByText("Native conversation 257", { exact: true });
    await app.screenshot("native-sessions-after-last-page");
    expect(await missingConversation.isVisible()).toBe(true);
  },
);
