import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Shortened titles and commit subjects omit an incomplete Chakma cluster", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("vowel-sign-proof");
  const titles: string[] = [];
  let selected = { threadId: "" };
  await browser.setViewport({ width: 1920, height: 1080 });
  for (const count of [77, 76]) {
    const started = await runPromise(makeState(T3_HOME).cli([
      "thread", "start", project, `${"a".repeat(count)}𑄇𑄧 and the rest of a long first line`,
      "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json",
    ]));
    selected = JSON.parse(started.stdout);
    await t3.open(selected);
    const heading = screen.getByRole("heading", /^a{76}/);
    await heading.waitFor();
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    titles.push(await heading.textContent() ?? "");
    await app.screenshot(`title-${count}-units`);
  }
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.writeFileString(`${project}/README.md`, "Synthetic change for vowel-sign proof.\n");
    yield* run("git", ["config", "user.name", "Scenario"], { cwd: project });
    yield* run("git", ["config", "user.email", "scenario@example.invalid"], { cwd: project });
  }));
  await screen.getByRole("button", "Git action options").tap();
  await screen.getByRole("button", "Changes Uncommitted +1 -0", { exact: true }).waitFor();
  await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill(`${"a".repeat(67)}𑄇𑄧bbbb`);
  await screen.getByRole("button", "Commit", { exact: true }).tap();
  await screen.getByText(/^Committed [0-9a-f]+$/).waitFor();
  await app.screenshot("commit-success-description");
  const description = await screen.getByText(/^a{67}/).last().textContent();
  expect({ titles, description }).toEqual({ titles: ["a".repeat(77) + "…", "a".repeat(76) + "…"], description: "a".repeat(67) + "..." });
});
