/// <reference lib="dom" />
// @effect-diagnostics nodeBuiltinImport:off -- The scenario starts 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 { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const ACP = `
import { createInterface } from "node:readline";

const sessionId = "image-question-session";
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
let promptId;
for await (const line of createInterface({ input: process.stdin })) {
  const { id, method } = JSON.parse(line);
  if (method === "session/cancel" && promptId !== undefined) {
    send({ id: promptId, result: { stopReason: "cancelled" } });
    promptId = undefined;
  }
  if (id === undefined || method === undefined) continue;
  if (method === "initialize") {
    send({ id, result: { protocolVersion: 1, agentCapabilities: { promptCapabilities: { image: true } }, authMethods: [],
      agentInfo: { name: "Question fixture", version: "1.0.0" } } });
  } else if (method === "session/new") {
    send({ id, result: { sessionId } });
  } else if (method === "session/prompt") {
    promptId = id;
    send({
      id: "ask-image-question",
      method: "elicitation/create",
      params: {
        sessionId,
        mode: "form",
        message: "What should we look at?",
        requestedSchema: {
          type: "object",
          properties: { answer: { type: "string", title: "Choose how the migration should roll out across regions. Consider the customers who are already using the service and explain which rollout strategy will keep their work safe. The complete header should remain readable while this question is expanded.", description: "Which rollout strategy should we use?", enum: ["One region first", "All regions together"] } },
          required: ["answer"],
        },
      },
    });
  } else {
    send({ id, error: { code: -32601, message: "Method not found" } });
  }
}
`;

test("Expanded question headers remain readable after reopening", WEB, async ({ t3, app, browser }) => {
    const project = await t3.project("demo", { "question-agent.mjs": ACP });
    const instanceId = ProviderInstanceId.make("scenario-question-agent");
    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: "Question fixture",
              enabled: true,
              config: {
                source: "local",
                commandPath: process.execPath,
                commandArgs: [NodePath.join(project, "question-agent.mjs")],
              },
            },
          },
        });
      }).pipe(Effect.scoped),
    );
    const { cli } = makeState(T3_HOME);
    const started = await runPromise(
      cli(
        [
          "thread",
          "start",
          project,
          "Ask me which rollout strategy to use.",
          "--title",
          "Migration rollout",
          "--provider",
          instanceId,
          "--model",
          "default",
          "--wait",
          "--json",
        ],
        [2],
      ),
    );
    const { threadId } = JSON.parse(started.stdout) as { threadId: string };
    const thread = { threadId };

    await browser.setViewport({ width: 820, height: 900 });
    await t3.open(thread);
    const toggle = browser.locator('[data-pending-user-input-toggle]');
    await toggle.waitFor({ timeout: 60000 });
    await app.screenshot("expanded-question");
    await toggle.click();
    await browser.locator('[data-pending-user-input-toggle="collapsed"]').waitFor();
    await app.screenshot("collapsed-question");
    await toggle.click();
    await browser.locator('[data-pending-user-input-toggle="expanded"]').waitFor();
    await app.screenshot("reexpanded-question");
    await expect.poll(() => browser.evaluate(() => {
      const label = document.querySelector('[data-pending-user-input-toggle="expanded"] span[dir]') as HTMLElement | null;
      return label !== null && label.scrollWidth <= label.clientWidth && label.scrollHeight <= label.clientHeight;
    })).toBe(true);

});
