import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Devin allows a typed Mango answer and receives it as q0", WEB, async ({ t3, app, screen, browser }) => {
  // Only instrument the replay model; both app revisions receive the same captured request.
  const agentPath = join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts");
  const original = await readFile(agentPath, "utf8");
  const params = {
    mode: "form",
    requestedSchema: { type: "object", properties: { q0: {
      type: "string", title: "Fruit", description: "Which fruit?",
      oneOf: [{ const: "Apple", title: "Apple" }, { const: "Banana", title: "Banana" }],
    } }, required: ["q0"] },
    message: "Which fruit?",
    _meta: { "cognition.ai/allowOther": true, "cognition.ai/toolCallId": "call_..." },
  };
  let replay = original.replace(
    'if (frame.kind === "request") {\n        await sleep',
    `if (frame.kind === "request") {\n        frame.params = { ...${JSON.stringify(params)}, sessionId };\n        await sleep`,
  );
  replay = replay.replace(
    'pendingAgentRequests.delete(String(id));\n        // The client',
    'pendingAgentRequests.delete(String(id));\n        send({ method: "session/update", params: { sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Replay agent received: " + JSON.stringify(answer) } } } });\n        // The client',
  );
  await writeFile(agentPath, replay);
  try {
    const project = await t3.project("Fruit demo");
    const thread = await t3.thread({ project, title: "Devin fruit question", messages: ["Ask which fruit: Apple, Banana, or my own answer."], model: "question" });
    await t3.open(thread);
    await screen.getByText("Which fruit?", { exact: true }).first().waitFor({ state: "visible" });
    const composer = screen.getByRole("textbox");
    await composer.tap();
    await browser.keyboard.type("Mango");
    await app.screenshot("typed-mango");
    await expect(composer).toContainText("Mango");
    await screen.getByRole("button", "Submit", { exact: true }).tap();
    await expect(screen.getByText('Replay agent received: {"action":"accept","content":{"q0":"Mango"}}', { exact: false })).toBeVisible();
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
    await app.screenshot("agent-received-mango");
  } finally {
    await writeFile(agentPath, original);
  }
});
