/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Failed partial commits retain exclusions through stash and retry", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("partial-commit", {"alpha.txt":"alpha before\n", "beta.txt":"beta before\n"});
  const git = (...args: string[]) => runPromise(run("git", args, {cwd: project}));
  const write = (name: string, text: string) => runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFileString(`${project}/${name}`, text)));
  await git("config", "user.name", "Scenario");
  await git("config", "user.email", "scenario@example.invalid");
  await git("config", "core.hooksPath", ".git/hooks");
  await git("branch", "other");
  await write("alpha.txt", "alpha after\n");
  await write("beta.txt", "beta after\n");
  await write(".git/hooks/pre-commit", "#!/bin/sh\necho 'Commit rejected for retry demonstration' >&2\nexit 1\n");
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.chmod(`${project}/.git/hooks/pre-commit`, 0o755)));
  const thread = await t3.thread({project, title:"Partial commit retry", messages:["Start"]});
  await browser.emulateMedia({colorScheme:"dark"});
  await browser.addInitScript(() => {
    // Redact the generated scratch checkout path in error notifications only.
    new MutationObserver(() => {
      for (const node of document.querySelectorAll('[role="dialog"]')) {
        const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
        while (walker.nextNode()) {
          const text = walker.currentNode;
          if (text.textContent?.includes("/partial-commit)")) text.textContent = text.textContent.replace(/\([^)]*partial-commit\)/g, "(scratch repository)");
        }
      }
    }).observe(document, {childList:true, subtree:true, characterData:true});
  });
  await t3.open(thread);
  const open = async () => {
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", {exact:true}).tap();
    await screen.getByRole("button", "Open beta.txt in editor", {exact:true}).waitFor();
    await screen.getByRole("button", "Edit", {exact:true}).tap();
  };
  const included = () => browser.evaluate(() => document.querySelector('[aria-label="Include beta.txt"]')?.getAttribute("aria-checked"));
  const exclude = () => screen.getByRole("checkbox", "Include beta.txt", {exact:true}).tap();
  await open();
  await exclude();
  await app.screenshot("001-selected-alpha");
  await screen.getByRole("button", "Cancel", {exact:true}).tap();
  await open();
  const afterCancel = await included();
  await app.screenshot("002-cancel-and-reopen");
  if (afterCancel === "true") await exclude();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill("only alpha");
  await screen.getByRole("button", "Commit", {exact:true}).tap();
  await screen.getByText("Action failed", {exact:true}).waitFor();
  await screen.getByRole("button", "Dismiss notification").tap();
  await open();
  const afterFailure = await included();
  await app.screenshot("003-reopened-after-failure");
  // Stash without closing the failed draft, then restore on the same branch.
  await git("stash", "push");
  await git("stash", "pop");
  await screen.getByRole("button", "Open beta.txt in editor", {exact:true}).waitFor();
  const afterStash = await included();
  await app.screenshot("004-same-branch-stash-restored");
  await write(".git/hooks/pre-commit", "#!/bin/sh\nexit 0\n");
  await screen.getByRole("button", "Commit", {exact:true}).tap();
  await expect.poll(async () => (await git("log", "-1", "--format=%s")).stdout.trim()).toBe("only alpha");
  const committed = (await git("show", "--format=", "--name-only", "HEAD")).stdout.trim();
  const remaining = (await git("diff", "--name-only", "HEAD")).stdout.trim();
  // Read the real repository through the app terminal, without exposing workspace paths.
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  await screen.getByLabel("Terminal input").focus();
  await browser.keyboard.type("PS1='$ '; clear; printf 'COMMITTED FILES\\n'; git show --format= --stat HEAD; printf '\\nREMAINING CHANGES\\n'; git diff --stat HEAD; printf '\\nRETRY COMPLETE\\n'; touch .git/proof-output-ready");
  await browser.keyboard.press("Enter");
  await expect.poll(async () => (await git("rev-parse", "--git-path", "proof-output-ready")).stdout && runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.exists(`${project}/.git/proof-output-ready`)))).toBe(true);
  await app.screenshot("005-retry-repository-result");
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  // A second failed draft switches branches while exclusions are retained.
  await git("reset", "--hard", "HEAD~1");
  await write("alpha.txt", "alpha after\n");
  await write("beta.txt", "beta after\n");
  await write(".git/hooks/pre-commit", "#!/bin/sh\nexit 1\n");
  await open();
  await exclude();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill("new branch alpha");
  await screen.getByRole("button", "Commit on new branch", {exact:true}).tap();
  await screen.getByText("Action failed", {exact:true}).waitFor();
  await screen.getByRole("button", "Dismiss notification").tap();
  await open();
  if (await included() === "true") await exclude();
  await app.screenshot("006-new-branch-failure-reopened");
  await git("checkout", "other");
  // Server's watcher must publish the new branch before observing the draft.
  await screen.getByRole("dialog", "Commit changes").getByText("other", {exact:true}).waitFor();
  await app.screenshot("007-different-branch-draft");
  const onOther = await included();
  if (onOther === "true") await exclude();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill("feature alpha only");
  await write(".git/hooks/pre-commit", "#!/bin/sh\nexit 0\n");
  await screen.getByRole("button", "Commit on new branch", {exact:true}).tap();
  await expect.poll(async () => (await git("log", "-1", "--format=%s")).stdout.trim()).toBe("feature alpha only");
  const featureFiles = (await git("show", "--format=", "--name-only", "HEAD")).stdout.trim();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  await screen.getByLabel("Terminal input").focus();
  await browser.keyboard.type("clear; printf 'NEW BRANCH COMMIT\\n'; git branch --show-current; git show --format= --stat HEAD; printf '\\nREMAINING CHANGES\\n'; git diff --stat HEAD; touch .git/feature-proof-ready");
  await browser.keyboard.press("Enter");
  await expect.poll(() => runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.exists(`${project}/.git/feature-proof-ready`)))).toBe(true);
  await app.screenshot("008-new-branch-commit-result");
  expect({afterCancel, afterFailure, afterStash, committed, remaining, onOther, featureFiles}).toEqual({afterCancel:"true", afterFailure:"false", afterStash:"false", committed:"alpha.txt", remaining:"beta.txt", onOther:"true", featureFiles:"alpha.txt"});
});
