import { mkdir, readFile, writeFile, symlink } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("POSIX executable with a literal backslash retains npm update actions", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.project("demo");
  const bin = join(T3_HOME, "bin");
  await mkdir(bin, { recursive: true });
  for (const name of ["cx-fast", "cx\\fast"]) {
    await symlink(process.env.CODEX_EVIDENCE_BINARY!, join(bin, name));
  }
  const settingsFile = join(T3_HOME, "userdata", "settings.json");
  const settings = JSON.parse(await readFile(settingsFile, "utf8"));
  settings.providerInstances.codex = { driver: "codex", enabled: true, config: { setupMode: "existing", binaryPath: "cx-fast" } };
  await writeFile(settingsFile, JSON.stringify(settings));
  await t3.open("/settings/providers?instanceId=codex");
  const update = screen.getByRole("button", "Update now", { exact: true });
  await expect(update).toBeVisible({ timeout: 60000 });
  await app.screenshot("control-hyphen-name");
  await browser.locator('input[id$="binaryPath"]').fill("cx\\fast");
  await browser.keyboard.press("Enter");
  await expect(screen.getByText("0.171.0", { exact: false }).last()).toBeVisible({ timeout: 60000 });
  // Reopen after the saved config has caused provider status to refresh.
  await t3.open("/settings/providers?instanceId=codex");
  const refresh = screen.getByRole("button", /Refresh provider status/);
  await refresh.tap();
  await expect(refresh).toBeEnabled({ timeout: 60000 });
  await app.screenshot("literal-backslash-update-actions");
  await expect(update).toBeVisible();
});
