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 CURSOR = "cursor-" + "x".repeat(3000);
const ACP = `
import { createInterface } from "node:readline";
const cursor = ${JSON.stringify(CURSOR)};
const reply = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
const handle = ({ method, params }) => {
  if (method === "initialize") return { protocolVersion: 1, agentInfo: { name: "long-cursor", version: "1" }, agentCapabilities: { sessionCapabilities: { list: {} } }, authMethods: [] };
  if (method === "session/new") return { sessionId: "probe" };
  if (method === "session/list") {
    if (params.cursor === undefined) return { sessions: Array.from({ length: 60 }, (_, i) => ({ sessionId: "native-" + i, cwd: params.cwd, title: "Native conversation " + (i + 1) })), nextCursor: cursor };
    if (params.cursor === cursor) return { sessions: [{ sessionId: "older", cwd: params.cwd, title: "Older conversation" }] };
    return { error: { code: -32000, message: "invalid cursor" } };
  }
  return undefined;
};
createInterface({ input: process.stdin }).on("line", (line) => { const request = JSON.parse(line); if (request.id === undefined) return; const result = handle(request); reply(result === undefined ? { id: request.id, error: { code: -32601, message: "Method not found" } } : { id: request.id, result }); });
`;

test("ACP session lists preserve long cursors for Load more", WEB, async ({ t3, app, screen }) => {
  const instanceId = ProviderInstanceId.make("long-cursor-agent");
  const project = await t3.project("demo", { "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: "Long cursor ACP", enabled: true, config: { source: "local", commandPath: process.execPath, commandArgs: [NodePath.join(project, "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 60", { exact: true }).waitFor();
  await screen.getByRole("button", "Load more", { exact: true }).tap();
  await app.screenshot("after-load-more");
  expect(await screen.getByText("Older conversation", { exact: true }).isVisible(), "The second ACP page loads with the opaque cursor").toBe(true);
});
