import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("An embedded-space key is rejected and leaves Ctrl+K active", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("shortcut-proof");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter(event => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some(provider => provider.instanceId === "devReplay" && provider.models?.some(model => model.slug === "multi-turn"));
      }), Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({ project, title: "Shortcut validation", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("Start", { exact: true }).waitFor();
  const palette = screen.getByRole("dialog", "Command palette");
  await browser.keyboard.press("Control+k");
  await palette.waitFor();
  await browser.keyboard.press("Escape");
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFileString(
    `${T3_HOME}/userdata/keybindings.json`,
    '[{"key":"mod+shift k","command":"commandPalette.toggle"}]\n',
  )));
  await t3.open("/settings/keybindings");
  await screen.getByLabel("Search keybindings").fill("Command Palette");
  await screen.getByRole("button", /^Edit shortcut for Command Palette: Toggle:/).waitFor();
  await app.screenshot("malformed-shortcut-settings");
  await t3.open(thread);
  await screen.getByText("Start", { exact: true }).tap();
  await browser.keyboard.press("Control+k");
  try {
    await expect(palette).toBeVisible();
  } finally {
    await browser.evaluate(async () => {
      await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
      await Promise.all(document.getAnimations().filter(animation => animation.effect?.getTiming().iterations !== Infinity).map(animation => animation.finished.catch(() => {})));
      return null;
    });
    await app.screenshot("ctrl-k-after-malformed-shortcut");
  }
});
