/// <reference lib="dom" />
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";

const MARKDOWN = '[a.ts](a/a.ts (first)) [a.ts](b/a.ts (second))\n\n[a.ts](c/a.ts "first") [a.ts](d/a.ts "second")';

test("Parenthesized file titles keep distinguishing folder labels", WEB, async ({t3, app, browser}) => {
  const project = await t3.project("proj", {
    "a/a.ts": "export const a = 1;\n", "b/a.ts": "export const b = 2;\n",
    "c/a.ts": "export const c = 3;\n", "d/a.ts": "export const d = 4;\n",
  });
  // Replay the exact reported assistant response through the real ACP adapter.
  const fixture = join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await readFile(fixture, "utf8");
  const transcript = [
    {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}},
    {type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:MARKDOWN}}}}},
    {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}},
  ].map(row => JSON.stringify(row)).join("\n") + "\n";
  let thread;
  try {
    await writeFile(fixture, transcript);
    thread = await t3.thread({project, title:"File title comparison", model:"command-output", messages:[`Reply outside a code block with exactly:\n${MARKDOWN}`]});
  } finally { await writeFile(fixture, original); }
  await t3.open(thread);
  await browser.locator('a').getByText("a.ts · proj/c", {exact:true}).waitFor();
  await browser.locator("text=Syncing messages...").waitFor({ state: "hidden" });
  await app.screenshot("file-title-folder-labels");
  const labels = await browser.evaluate(() => [...document.querySelectorAll("a")].map(a=>a.textContent?.trim()).filter(text=>text?.startsWith("a.ts")));
  expect(labels).toContain("a.ts · proj/a");
  expect(labels).toContain("a.ts · proj/b");
});
