import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { test, WEB } from "./t3.ts";

test("Committing 1600 long paths leaves only the excluded README uncommitted", WEB,
  async ({ t3, app, screen, browser }) => {
    const prefix = Array.from({ length: 7 }, (_, i) => `${i}-` + "a".repeat(193)).join("/");
    const files = Object.fromEntries(Array.from({ length: 1600 }, (_, i) =>
      [`${prefix}/file-${String(i).padStart(4, "0")}.txt`, "original\n"]));
    const repo = await t3.project("Large selection", files);
    const git = (...args: string[]) => execFileSync("git", args, { cwd: repo, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).trim();
    git("config", "user.name", "Scenario");
    git("config", "user.email", "scenario@example.invalid");
    for (const path of Object.keys(files)) writeFileSync(join(repo, path), "original\nadded\n");
    writeFileSync(join(repo, "README.md"), "Excluded change\n");
    await t3.open();
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
    await screen.getByRole("button", "Edit", { exact: true }).tap();
    await browser.locator('div:has(> button[aria-label="Open README.md in editor"])').getByRole("checkbox").tap();
    await screen.getByPlaceholder("Leave empty to auto-generate").fill("Update sample files");
    await app.screenshot("selected-files");
    await screen.getByRole("button", "Commit", { exact: true }).tap();
    let capturedError = false;
    try {
      await expect.poll(async () => {
        if (!capturedError && await screen.getByText("spawn E2BIG", { exact: false }).first().isVisible()) {
          await app.screenshot("commit-result");
          capturedError = true;
        }
        return git("log", "-1", "--format=%s");
      }, { timeout: 20000, message: "The selected-file commit must finish" }).toBe("Update sample files");
      await expect(screen.getByText("+1", { exact: true })).toBeVisible();
    } finally {
      if (!capturedError) await app.screenshot("commit-result");
    }
    expect(git("status", "--porcelain")).toBe("M README.md");
    expect(git("diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD").split("\n").length).toBe(1600);
  });
