/// <reference lib="dom" />
import { expect } from "e2e";
import { writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { test, WEB } from "./t3.ts";

const lines = (n: number) => Array.from({ length: n }, (_, i) => `${i + 1}\n`).join("");
test("Exact half-step diff counts round upward", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("diff-rounding");
  writeFileSync(`${project}/lines-1150.txt`, lines(1150));
  writeFileSync(`${project}/lines-9950.txt`, lines(9950));
  const thread = await t3.thread({ project, title: "Half-step diff counts", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByText("Diff", { exact: true }).tap();
  await screen.getByRole("group", "9950 additions, 0 deletions", { exact: true }).waitFor();
  await app.screenshot("half-step-additions");
  const read = () => browser.evaluate(() => Array.from(document.querySelectorAll('[role="group"][aria-label$="deletions"]'), el => ({ label: el.getAttribute("aria-label"), text: el.textContent })));
  const additions = await read();
  execFileSync("git", ["add", "lines-9950.txt"], { cwd: project });
  execFileSync("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Seed deletion count"], { cwd: project });
  writeFileSync(`${project}/lines-9950.txt`, lines(8800));
  writeFileSync(`${project}/lines-1150000.txt`, lines(1150000));
  await screen.getByRole("button", "Refresh diff", { exact: true }).tap();
  await screen.getByRole("group", "1150000 additions, 0 deletions", { exact: true }).waitFor();
  await app.screenshot("half-step-deletions-and-millions");
  const final = await read();
  expect(additions.find(x => x.label === "1150 additions, 0 deletions")?.text).toBe("+1.2k-0");
  expect(additions.find(x => x.label === "9950 additions, 0 deletions")?.text).toBe("+10k-0");
  expect(final.find(x => x.label === "0 additions, 1150 deletions")?.text).toBe("+0-1.2k");
  expect(final.find(x => x.label === "1150000 additions, 0 deletions")?.text).toBe("+1.2m-0");
  expect(final.find(x => x.label === "1151150 additions, 1150 deletions")?.text).toBe("+1.2m-1.2k");
});
