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

test("Merging removes agent credits without changing retained line separators", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("mixed-endings");
  const command = async (program: string, args: string[]) => (await runPromise(run(program, args, { cwd: project }))).stdout;
  const git = (...args: string[]) => command("git", args);
  const branch = `proof-${Date.now()}`;
  await git("remote", "add", "origin", "https://gitlab.com/julius54/t3-mixed-endings-proof-46620.git");
  await git("fetch", "origin", "main");
  await git("reset", "--hard", "origin/main");
  await git("switch", "-c", branch);
  await writeFile(`${project}/sample.txt`, branch);
  await git("add", "sample.txt");
  await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--cleanup=verbatim", "-m", "Add a\n\nDetails line one\r\nDetails line two\r\n\r\nCo-authored-by: Claude <noreply@anthropic.com>\r\n");
  await git("push", "-u", "origin", branch);
  const mr = JSON.parse(await command("glab", ["api", "-X", "POST", "projects/89705266/merge_requests", "-f", `source_branch=${branch}`, "-f", "target_branch=main", "-f", "title=Repro mixed endings"]));
  const thread = await t3.thread({ project, title: "Mixed line endings merge", messages: ["Ready to merge"] });
  await t3.open("/settings/source-control");
  await screen.getByRole("switch", "Remove agent credits when merging").tap();
  await t3.open(thread);
  await browser.locator(`a[href='${mr.web_url}']`).first().tap();
  await screen.getByRole("button", "Merge", { exact: true }).tap();
  await screen.getByRole("button", "Confirm merge?", { exact: true }).tap();
  let merged: {state: string; squash_commit_sha: string};
  await expect.poll(async () => {
    merged = JSON.parse(await command("glab", ["api", `projects/89705266/merge_requests/${mr.iid}`]));
    return merged.state;
  }, { timeout: 60000 }).toBe("merged");
  await expect(screen.getByRole("button", "Merging...", { exact: true })).not.toBeVisible({ timeout: 60000 });
  const rawFetch = await git("fetch", "origin", "main");
  const raw = await git("cat-file", "commit", merged!.squash_commit_sha);
  const message = raw.slice(raw.indexOf("\n\n") + 2);
  const expected = "Repro mixed endings\n\nAdd a\n\nDetails line one\r\nDetails line two\n";
  const report = `STORED SQUASH COMMIT MESSAGE (escaped bytes)\n${message.match(/[^\n]*\n|[^\n]+$/g)?.map((line, index) => `${index + 1}: ${JSON.stringify(line)}`).join("\n")}\n\nExpected retained separators: LF, LF, LF, LF, CRLF\nObserved: ${message === expected ? "PRESERVED" : "REWRITTEN"}\nAgent credit removed: ${!message.includes("Co-authored-by")}\n`;
  await writeFile(`${project}/.git/merge-proof.txt`, report);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await input.focus();
  await browser.keyboard.type("PS1='$ '; clear; cat .git/merge-proof.txt; touch .git/rendered\n");
  await expect.poll(() => readFile(`${project}/.git/rendered`, "utf8").catch(() => "pending")).toBe("");
  await app.screenshot("stored-merge-message");
  await expect(message).toBe(expected);
});
