import { expect } from "e2e";
import { mkdir, rename, symlink, writeFile, readFile } from "node:fs/promises";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Selected-file commits through a symlink preserve an ongoing merge", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Merge-demo", { "base.txt": "base\n" });
  const real = `${project}-real`;
  await rename(project, real);
  await mkdir(`${real}/nested`);
  await symlink(`${real}/nested`, project);
  const git = async (...args: string[]) => (await runPromise(run("git", args, { cwd: real }))).stdout.trim();
  await git("config", "user.name", "Scenario");
  await git("config", "user.email", "scenario@example.invalid");
  await git("checkout", "-b", "feature");
  await writeFile(`${real}/feature.txt`, "feature\n");
  await git("add", "feature.txt");
  await git("commit", "-m", "Feature");
  await git("checkout", "main");
  await writeFile(`${real}/main.txt`, "main\n");
  await git("add", "main.txt");
  await git("commit", "-m", "Main");
  await git("merge", "--no-commit", "--no-ff", "feature");
  await writeFile(`${real}/unrelated.txt`, "unrelated\n");
  const snapshot = async () => ({ head: await git("rev-parse", "HEAD"), index: await git("ls-files", "--stage"), status: await git("status", "--porcelain"), merge: await readFile(`${real}/.git/MERGE_HEAD`, "utf8").catch(() => "MISSING"), files: await Promise.all(["base", "feature", "main", "unrelated"].map(f => readFile(`${real}/${f}.txt`, "utf8"))) });
  const before = await snapshot();
  const thread = await t3.thread({ project, title: "Selected-file merge commit", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Git action options").tap();
  await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
  await screen.getByRole("button", "Open unrelated.txt in editor").waitFor();
  await screen.getByRole("button", "Edit", { exact: true }).tap();
  await screen.getByRole("checkbox", "Include unrelated.txt").tap();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill("commit only feature.txt");
  await app.screenshot("selected-file-commit");
  // Presentation-only privacy redaction: retain the real error and expand its clamped text.
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.textContent = '[data-slot="toast-description"] { -webkit-line-clamp: unset !important; display: block !important; }';
    document.head.append(style);
    const redact = () => document.querySelectorAll('[data-slot="toast-description"]').forEach(node => {
      const text = node.textContent ?? "";
      const safe = text.replace(/\(\/[^)]*\)/g, "([synthetic fixture path redacted])");
      if (safe !== text) node.textContent = safe;
    });
    new MutationObserver(redact).observe(document.body, { childList: true, subtree: true, characterData: true });
  });
  await screen.getByRole("button", "Commit", { exact: true }).tap();
  await screen.getByText(/^(Committed [0-9a-f]+|Action failed)$/).waitFor();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
  });
  await app.screenshot("merge-commit-result");
  await expect(screen.getByText(/Cannot commit selected files during a merge\. Commit all files to finish the merge\./)).toBeVisible();
  expect(await snapshot()).toEqual(before);
});
