/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Codex file URL decodes percent escapes while a literal path preserves them", WEB, async ({ t3, app, browser, screen }) => {
  const lines = (marker: string) => `// line 1\n// line 2\n// line 3\n// line 4\n// line 5\n// line 6\n${marker}\n`;
  const project = await t3.project("citation-demo", {
    "a b.ts": lines("SPACE_NAMED_FILE"),
    "a%20b.ts": lines("PERCENT_NAMED_FILE"),
  });
  const input = { project, title: "File URL versus literal path", model: "multi-turn", messages: [
    `A — file URL: :codex-file-citation{path="file://${project}/a%20b.ts" line_range_start="7"}\n\nB — literal path: :codex-file-citation{path="${project}/a%20b.ts" line_range_start="7"}`,
  ] };
  let thread;
  try { thread = await t3.thread(input); }
  catch (error) {
    if (!String(error).includes("Advertised models: default")) throw error;
    thread = await t3.thread({ ...input, model: "default" });
  }
  await t3.open(thread);
  await screen.getByRole("button", /^Agent A/).tap();
  const editorText = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  });
  const citations = screen.getByRole("link", /^a(?: |%20)b\.ts/);
  await citations.first().tap();
  let urlText = "";
  try {
    await expect.poll(editorText).toMatch(/(?:SPACE|PERCENT)_NAMED_FILE/);
    urlText = await editorText();
  } finally { await app.screenshot("A-file-URL-line-7"); }
  await citations.last().tap();
  let literalText = "";
  try {
    await expect.poll(editorText).toContain("PERCENT_NAMED_FILE");
    literalText = await editorText();
  } finally { await app.screenshot("B-literal-path-line-7"); }
  expect(urlText).toContain("SPACE_NAMED_FILE");
  expect(literalText).toContain("PERCENT_NAMED_FILE");
  await expect(citations.first()).toHaveText("a b.ts · L7");
});
