/// <reference lib="dom" />
import { WS_METHODS, type ServerSettings } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";

import { T3_HOME } from "../e2e.config.ts";
import { environmentId, rpcClient, runPromise, test, WEB } from "./t3.ts";

function matchingActions(settings: ServerSettings) {
  return Object.values(settings.projectSettingsOverrides)
    .flatMap((entry) => entry.defaultProjectScripts ?? [])
    .filter((script) => script.name === "Run smoke checks");
}

const readConfig = (origin: string) =>
  runPromise(
    Effect.scoped(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, origin);
        return yield* client[WS_METHODS.serverGetConfig]({});
      }),
    ),
  );

test(
  "Retrying a shortcut file error saves the shortcut for the original action",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const remote = { ".git/config": '[remote "origin"]\nurl = https://github.com/example/retry-demo.git\n' };
    const project = await t3.project("demo", remote);
    const second = await t3.project("demo-checkout", remote);
    await t3.thread({ project: second, title: "Second checkout", messages: ["Start"] });
    const thread = await t3.thread({ project, title: "Project work", messages: ["Start"] });
    const origin = app.baseUrl ?? "";
    const { keybindingsConfigPath } = await readConfig(origin);
    const original = await runPromise(
      Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(keybindingsConfigPath)),
    );
    const writeKeybindings = (contents: string) =>
      runPromise(
        Effect.flatMap(FileSystem.FileSystem, (fs) =>
          fs.writeFileString(keybindingsConfigPath, contents),
        ),
      );

    await browser.setViewport({ width: 1920, height: 1000 });
    await browser.addInitScript(() => {
      // Keep the actual failure visible while removing only the machine-local filename prefix.
      new MutationObserver(() => {
        if (!document.body) return;
        const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
        while (walk.nextNode()) {
          const node = walk.currentNode;
          const before = node.textContent ?? "";
          const after = before.replace(/\/[^\s:]*\/keybindings\.json/g, "keybindings.json")
            .replace(/\/home\/[^\s:]*?\/workspaces\/w-[^/\s]+/g, "/workspace");
          if (before !== after) node.textContent = after;
        }
      }).observe(document, { childList: true, subtree: true, characterData: true });
    });
    await t3.open(thread);
    await screen.getByRole("button", "Add project script", { exact: true }).tap();
    await browser.locator("#script-name").fill("Run smoke checks");
    await browser.locator("#script-command").fill("echo checks");
    await browser.locator("#script-keybinding").press("Control+Shift+7");
    const editor = browser.locator('[data-slot="dialog-popup"][data-open]:has(#script-name)');
    const save = editor.getByRole("button", "Save action", { exact: true });

    let firstSettings;
    try {
      await writeKeybindings("{invalid JSON");
      await save.tap();
      await editor.getByText(/Unable to parse keybindings config/).waitFor();
      firstSettings = (await readConfig(origin)).settings;
    } finally {
      await writeKeybindings(original);
    }

    const firstActions = matchingActions(firstSettings);
    
    const actionId = firstActions[0]!.id;
    await save.tap();
    await browser.locator("#script-name").waitFor({ state: "hidden" });
    await screen.getByRole("button", "Script actions", { exact: true }).tap();
    await screen
      .getByRole("menuitem", /^Run smoke checks/)
      .first()
      .waitFor();
    await app.screenshot("actions-after-retrying-save");

    const threadConfig = await readConfig(origin);
    // Settings applies one creation to both checkouts; a shortcut failure interrupts the first target.
    await t3.open("/settings/projects?project=" + encodeURIComponent("github.com/example/retry-demo"));
    await screen.getByRole("button", "Add action", { exact: true }).tap();
    await browser.locator("#script-name").fill("Settings smoke checks");
    await browser.locator("#script-command").fill("echo settings");
    await browser.locator("#script-keybinding").press("Control+Shift+8");
    let settingsFirst;
    try {
      await writeKeybindings("{invalid JSON");
      await save.tap();
      await editor.getByText(/Unable to parse keybindings config/).waitFor();
      settingsFirst = (await readConfig(origin)).settings;
    } finally {
      await writeKeybindings(original);
    }
    await save.tap();
    await browser.locator("#script-name").waitFor({ state: "hidden" });
    await screen.getByRole("button", "Add action", { exact: true }).waitFor();
    const envId = await runPromise(environmentId(origin));
    for (const [index, checkout] of [project, second].entries()) {
      await t3.open("/settings/projects?project=" + encodeURIComponent("github.com/example/retry-demo") + "&checkout=" + encodeURIComponent(`${envId}:${checkout}`));
      await screen.getByRole("button", "Edit Settings smoke checks", { exact: true }).first().waitFor();
      await browser.evaluate(() => {
        document.getElementById("project-actions")?.scrollIntoView({block: "center"});
        // Capture after the dialog and scroll transitions finish, without changing app behavior.
        return Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))).then(() => null);
      });
      await app.screenshot(`settings-checkout-${index + 1}-after-retrying-save`);
    }
    const config = await readConfig(origin);
    const settingsId = Object.values(settingsFirst.projectSettingsOverrides)
      .flatMap(e => e.defaultProjectScripts ?? []).find(s => s.name === "Settings smoke checks")!.id;
    const lists = Object.values(config.settings.projectSettingsOverrides)
      .map(e => e.defaultProjectScripts ?? []);
    const settingsResult = lists.map(scripts => scripts.filter(s => s.name === "Settings smoke checks").map(s => s.id));
    expect(lists.some(scripts => scripts.some(s => s.id === actionId && s.command === "echo checks")), "Settings retry preserves the unrelated thread action").toBe(true);
    expect(config.keybindings.some(({command,shortcut}) => command === `script.${settingsId}.run` && shortcut.key === "8" && shortcut.modKey && shortcut.shiftKey), "Settings shortcut belongs to the original ID").toBe(true);
    expect(settingsResult, "Each checkout reuses the action identity after a partially completed Settings save").toEqual([[settingsId], [settingsId]]);
    expect(matchingActions(threadConfig.settings).map(s => s.id), "Thread retry keeps one original action").toEqual([actionId]);
    
    expect(
      threadConfig.keybindings.some(
        ({ command, shortcut }) =>
          command === `script.${actionId}.run` &&
          shortcut.key === "7" &&
          shortcut.shiftKey &&
          shortcut.modKey,
      ),
    ).toBe(true);
  },
);
