import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Editing a symlink target reloads Mod+K in the running app", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("shortcut-demo");
  const thread = await t3.thread({ project, title: "Symlink shortcut reload", messages: ["Hello"], model: "default" });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").waitFor();
  if (!(await fs.lstat(`${T3_HOME}/userdata/keybindings.json`)).isSymbolicLink()) throw new Error("Startup link was replaced");
  await browser.keyboard.press("Control+k");
  await screen.getByRole("dialog").waitFor();
  await app.screenshot("initial-mod-k-command-palette");
  await browser.keyboard.press("Escape");
  await fs.writeFile(`${T3_HOME}/dotfiles/keybindings.json`, '[{ "key": "mod+k", "command": "terminal.toggle" }]');
  // Match the reported 12-second interval before testing the edited shortcut.
  await new Promise(resolve => setTimeout(resolve, 12000));
  await browser.keyboard.press("Control+k");
  try {
    await expect(screen.getByLabel("Terminal input")).toBeVisible();
  } finally {
    await app.screenshot("mod-k-after-target-edit");
  }
});
