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

test("ACP tool details display inner text instead of content wrapper JSON", WEB, async ({ t3, app, screen }) => {
  const file = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await fs.readFile(file, "utf8");
  const update = (value: unknown, afterMs = 0) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: value } }, afterMs });
  const transcript = [
    { type: "transcript_start", provider: "acpRegistry", protocol: "acp.ndjson-jsonrpc", version: "1", scenario: "acp-content-proof" },
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    update({ sessionUpdate: "tool_call", toolCallId: "e9-other", kind: "other", title: "Fetching your cloud config", status: "in_progress" }),
    update({ sessionUpdate: "tool_call_update", toolCallId: "e9-other", status: "completed", content: [{ type: "content", content: { type: "text", text: "Cloud config is up to date." } }] }, 300),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Done." } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  await fs.writeFile(file, transcript.map(entry => JSON.stringify(entry)).join("\n") + "\n");
  try {
    const project = await t3.project("demo");
    const thread = await t3.thread({ project, title: "Cloud config", messages: ["check my cloud config"], model: "command-output" });
    await t3.open(thread);
    await screen.getByText("Done.", { exact: true }).waitFor();
    await screen.getByRole("button", "Worked for", { exact: false }).tap();
    await screen.getByRole("button", "Fetching your cloud config", { exact: false }).tap();
    await screen.getByText("Syncing messages…", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot("expanded-cloud-config");
    await expect(screen.getByText("Cloud config is up to date.", { exact: true })).toBeVisible();
  } finally {
    await fs.writeFile(file, original);
  }
});
