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

const reply = `Both entry points changed: [index.ts](src/server/index.ts "The server's entry") and [index.ts](src/client/index.ts).`;

test("Opposite quotes in file-link titles keep folder labels and searchable folders", WEB, async ({ t3, app, screen, browser }) => {
  const recording = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = await readFile(recording, "utf8");
  await writeFile(recording, [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: reply } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map(value => JSON.stringify(value)).join("\n") + "\n");
  try {
    const project = await t3.project("entry-points", { "src/server/index.ts": "export {};\n", "src/client/index.ts": "export {};\n" });
    const thread = await t3.thread({ project, title: "Entry point review", model: "command-output", messages: ["Review both entry points."] });
    await t3.open(thread);
    await screen.getByText("Both entry points changed:", { exact: false }).waitFor();
    await app.screenshot("file-link-folder-labels");
    await browser.keyboard.press("Control+f");
    await screen.getByRole("searchbox", "Find in thread").fill("src/server");
    try {
      await expect.poll(() => browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""'), { message: "The folder suffix is searchable" }).toBe("1/1");
    } finally {
      await app.screenshot("folder-search");
    }
    await expect(screen.getByText("index.ts · src/server", { exact: true })).toBeVisible();
    await expect(screen.getByText("index.ts · src/client", { exact: true })).toBeVisible();
  } finally {
    await writeFile(recording, original);
  }
});
