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

test(
  "Default shortcuts can be unassigned, reused, reset and reactivated",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("Shortcut demo");
    const thread = await t3.thread({ project, title: "Keyboard work", messages: ["Start"] });
    await t3.open("/settings/keybindings");
    const search = screen.getByRole("searchbox", "Search keybindings");
    const filter = async (text: string) => {
      await search.fill(text);
    };
    const stash = () => screen.getByRole("button", { name: /Edit shortcut for Composer: Stash:/ });
    const actions = (name: string) => screen.getByRole("button", `Actions for ${name}`);
    const unassign = async (name: string) => {
      await actions(name).tap();
      await screen.getByRole("menuitem", "Unassign").tap();
    };
    await filter("Composer: Stash");
    await stash().waitFor();
    await app.screenshot("01-default-stash");
    await expect(actions("Composer: Stash")).toHaveCount(1);
    await actions("Composer: Stash").tap();
    await app.screenshot("02-unassign-action");
    await expect(screen.getByRole("menuitem", "Unassign")).toBeVisible();
    await screen.getByRole("menuitem", "Unassign").tap();
    await expect(stash()).toHaveAccessibleName("Edit shortcut for Composer: Stash: Unassigned");
    await app.screenshot("03-stash-unassigned");
    await filter("Thread: Settle");
    await screen.getByRole("button", { name: /Edit shortcut for Thread: Settle:/ }).tap();
    await browser.keyboard.press("Control+s");
    await screen.getByRole("button", "Save", { exact: true }).tap();
    await expect(
      screen.getByRole("button", "Edit shortcut for Thread: Settle: Ctrl+S"),
    ).toBeVisible();
    await app.screenshot("04-shortcut-reused");
    const restartServer = async () => {
      const runtimePath = `${T3_HOME}/userdata/server-runtime.json`;
      const previous = JSON.parse(await readFile(runtimePath, "utf8")).pid;
      const now = new Date();
      await utimes(`${APP_DIR}/apps/server/package.json`, now, now);
      await expect
        .poll(
          async () => {
            try {
              return JSON.parse(await readFile(runtimePath, "utf8")).pid;
            } catch {
              return previous;
            }
          },
          { timeout: 60000 },
        )
        .not.toBe(previous);
      await t3.open("/settings/keybindings");
    };
    await restartServer();
    await filter("Composer: Stash");
    await expect(stash()).toHaveAccessibleName("Edit shortcut for Composer: Stash: Unassigned");
    await app.screenshot("05-unassigned-after-server-restart");
    await t3.open(thread);
    const composer = screen.getByTestId("composer-editor");
    await composer.tap();
    await composer.pressSequentially("This draft must not be stashed");
    await browser.keyboard.press("Control+s");
    await expect(composer).toHaveText("This draft must not be stashed");
    await screen.getByText("Settled", { exact: true }).first().waitFor();
    await t3.open(thread);
    await expect(composer).toHaveText("This draft must not be stashed");
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot("05-reused-shortcut-does-not-stash");
    await t3.open("/settings/keybindings");
    await filter("Thread: Settle");
    await actions("Thread: Settle").tap();
    await screen.getByRole("menuitem", "Reset to default").tap();
    await filter("Composer: Stash");
    await actions("Composer: Stash").tap();
    await app.screenshot("05-reset-menu");
    await screen.getByRole("menuitem", "Reset to default").tap();
    await expect(stash()).toHaveAccessibleName("Edit shortcut for Composer: Stash: Ctrl+S");
    await app.screenshot("06-reset-to-default");
    await unassign("Composer: Stash");
    await stash().tap();
    await screen.getByRole("textbox", "Keybinding for Composer: Stash").fill("ctrl+alt+s");
    await search.tap();
    await app.screenshot("07-typed-shortcut-draft");
    await screen.getByRole("button", "Save", { exact: true }).tap();
    await expect(stash()).toHaveAccessibleName("Edit shortcut for Composer: Stash: Ctrl+Alt+S");
    await app.screenshot("08-typed-shortcut-reactivated");
    await actions("Composer: Stash").tap();
    await screen.getByRole("menuitem", "Reset to default").tap();
    await unassign("Composer: Stash");
    await stash().tap();
    await browser.keyboard.press("Control+Shift+Alt+s");
    await screen.getByRole("button", "Save", { exact: true }).tap();
    await expect(stash()).toHaveAccessibleName(
      "Edit shortcut for Composer: Stash: Ctrl+Alt+Shift+S",
    );
    await app.screenshot("09-recorded-shortcut-reactivated");
    const configPath = `${T3_HOME}/userdata/keybindings.json`;
    await writeFile(
      configPath,
      JSON.stringify(
        Array.from({ length: 256 }, (_, index) => ({
          key: "mod+alt+f1",
          command: `script.filler-${index}.run`,
        })),
      ),
    );
    await t3.open("/settings/keybindings");
    await filter("composer.sendBackground");
    await app.screenshot("10-full-config-before-unassign");
    const response = await browser.evaluate(async () => {
      const { serverEnvironment } = await import("/src/state/server.ts");
      const { appAtomRegistry } = await import("/src/rpc/atomRegistry.ts");
      const { environmentId } = await (await fetch("/.well-known/t3/environment")).json();
      const result = await serverEnvironment.upsertKeybinding.run(appAtomRegistry, {
        environmentId,
        input: {
          command: "composer.sendBackground",
          key: "mod+enter",
          when: "false",
          replace: {
            command: "composer.sendBackground",
            key: "mod+enter",
            when: "composerFocus && draftThreadRoute",
          },
        },
      });
      return { _tag: result._tag };
    });
    expect(response._tag).toBe("Success");
    const background = screen.getByRole("button", {
      name: /Edit shortcut for Composer: Start in Background:/,
    });
    await expect(
      screen.getByRole("button", "Edit shortcut for Composer: Start in Background: Unassigned"),
    ).toBeVisible();
    const saved = JSON.parse(await readFile(configPath, "utf8"));
    expect(saved.length).toBe(256);
    expect(saved.filter((r: any) => r.command === "composer.sendBackground").length).toBe(2);
    await app.screenshot("11-full-config-sibling-preserved");
    const backgroundRules = saved.filter((r: any) => r.command === "composer.sendBackground");
    expect(backgroundRules).toEqual([
      {
        key: "mod+alt+enter",
        command: "composer.sendBackground",
        when: "composerFocus && draftThreadRoute",
      },
      { key: "mod+enter", command: "composer.sendBackground", when: "false" },
    ]);
    await writeFile(configPath, JSON.stringify(backgroundRules));
    await writeFile(`${T3_HOME}/userdata/keybindings-migrations`, "");
    await restartServer();
    await filter("composer.sendBackground");
    await expect(
      screen.getByRole("button", "Edit shortcut for Composer: Start in Background: Unassigned"),
    ).toHaveCount(1);
    await expect(background).toHaveCount(2);
    await app.screenshot("12-late-default-stays-unassigned-after-restart");
    const restarted = JSON.parse(await readFile(configPath, "utf8"));
    await writeFile(
      `${T3_HOME}/keybinding-server-transcript.json`,
      JSON.stringify(
        {
          environment: "Chromium 1280x800, light theme, isolated real server, synthetic data",
          capacity: {
            before: 256,
            after: saved.length,
            retainedFillers: saved.filter((r: any) => r.command.startsWith("script.filler-"))
              .length,
            firstRetainedFiller: saved[1],
            backgroundRules,
          },
          restart: {
            fixture:
              "only the two background rules, migration marker empty; ample capacity for a late default",
            afterCount: restarted.length,
            backgroundRules: restarted.filter((r: any) => r.command === "composer.sendBackground"),
            appliedMigrations: await readFile(`${T3_HOME}/userdata/keybindings-migrations`, "utf8"),
          },
        },
        null,
        2,
      ),
    );
  },
);
