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

const MESSAGE = String.raw`Two files share a name: [a.ts](src/a.ts "say \"hello\"") [a.ts](lib/a.ts).`;

test("Escaped quotes in a file title keep folder disambiguation", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("repo", { "src/a.ts": "export const a = 1;", "lib/a.ts": "export const a = 2;" });
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await fs.readFile(fixture, "utf8");
  try {
    await fs.writeFile(fixture, [
      { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
      { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: MESSAGE } } } } },
      { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
    ].map((entry) => JSON.stringify(entry)).join("\n"));
    const thread = await t3.thread({ project, title: "Escaped title file links", messages: ["Reply exactly with the two same-named file links."], model: "showcase" });
    await t3.open(thread);
    await screen.getByText("Two files share a name:", { exact: false }).waitFor();
    await screen.getByText(/^Syncing messages/).waitFor({ state: "hidden" });
    await app.screenshot("escaped-title-file-labels");
    await expect(screen.getByText("a.ts · repo/src", { exact: true })).toBeVisible();
    await expect(screen.getByText("a.ts · repo/lib", { exact: true })).toBeVisible();
  } finally {
    await fs.writeFile(fixture, original);
  }
});
