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

test("Codex tool diff keeps both files when the first path contains BEL", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("patch-demo");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.codex = { driver: "codex", enabled: true, config: { binaryPath: "/usr/local/bin/codex" } };
  await writeFile(settingsPath, JSON.stringify(settings));
  const started = await runPromise(makeState(T3_HOME).cli([
    "thread", "start", project,
    "Use ONE apply_patch call to create exactly two files: odd\u0007name.txt (the filename contains a real BEL U+0007 character between odd and name), and z-normal.txt. Each file must contain exactly hello followed by a newline. Do not use shell commands to write files. Use apply_patch with both Add File entries in one call. Then stop.",
    "--title", "Two-file patch", "--provider", "codex", "--model", "gpt-6.1-sol", "--wait", "--json"
  ]));
  const thread = JSON.parse(started.stdout);
  await t3.open(thread);
  await screen.getByRole("button", /Worked for/).tap();
  await screen.getByRole("button", "Changed 2 files", { exact: true }).tap();
  await screen.getByRole("button", "Open diff").tap();
  await screen.getByRole("button", /Collapse .*name\.txt/).hover();
  await screen.getByRole("button", "Changed 2 files", { exact: true }).tap();
  // Redact only the private workspace prefix in displayed text for public captures.
  await browser.evaluate((prefix: string) => {
    const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
    while (walker.nextNode()) {
      const node = walker.currentNode;
      if (node.textContent?.includes(prefix)) node.textContent = node.textContent.replaceAll(prefix, "/demo/patch-demo");
    }
  }, project);
  await app.screenshot("tool-diff");
  await expect(screen.getByText("z-normal.txt", { exact: true })).toBeVisible();
  await expect(screen.getByText("The recorded patch omits", { exact: false })).toBeHidden();
});
