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

test("Retargeted keybindings symlink follows subsequent target saves without restarting", WEB, async ({ t3, app, screen }) => {
  await t3.project("shortcut-demo");
  await t3.open("/settings/keybindings");
  await screen.getByLabel("Search keybindings").fill("Terminal: Toggle");
  const shortcut = (key: string) => screen.getByRole("button", `Edit shortcut for Terminal: Toggle: Ctrl+${key}`, { exact: true });
  await shortcut("K").waitFor();
  await app.screenshot("initial-target-A-ctrl-k");
  const root = `${T3_HOME}/userdata`;
  await symlink("B/keys.json", `${root}/keybindings.json.next`);
  await rename(`${root}/keybindings.json.next`, `${root}/keybindings.json`);
  await shortcut("J").waitFor();
  await app.screenshot("retargeted-to-B-ctrl-j");
  const editB = async (key: string) => {
    const rules = JSON.parse(await readFile(`${root}/B/keys.json`, "utf8"));
    await writeFile(`${root}/B/keys.json`, JSON.stringify(rules.map((rule: { command: string; key: string }) => rule.command === "terminal.toggle" ? { ...rule, key } : rule)));
  };
  await editB("mod+l");
  let firstSaveUpdated = false;
  try { await expect(shortcut("L")).toBeVisible(); firstSaveUpdated = true; }
  catch { /* Continue the reported old-target control before returning the bug assertion. */ }
  await app.screenshot("new-target-saved-mod-l");
  const oldContents = await readFile(`${root}/A/keys.json`, "utf8");
  await writeFile(`${root}/A/keys.json`, oldContents);
  await shortcut("L").waitFor();
  await app.screenshot("old-target-control");
  await editB("mod+u");
  let secondSaveUpdated = false;
  try { await expect(shortcut("U")).toBeVisible(); secondSaveUpdated = true; }
  catch { /* Preserve the second stale state in the video and screenshot. */ }
  await app.screenshot("second-new-target-save-mod-u");
  await writeFile(`${root}/A/keys.json`, oldContents);
  await shortcut("U").waitFor();
  await app.screenshot("second-old-target-control");
  expect(firstSaveUpdated && secondSaveUpdated).toBe(true);
});
