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(
  "A rejected commit-all keeps what a terminal staged while the hook ran",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo");
    const thread = await t3.thread({ project, title: "Commit all", messages: ["Start"] });
    const git = (...args: string[]) => run("git", args, { cwd: project });

    await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        yield* git("config", "user.name", "Scenario");
        yield* git("config", "user.email", "scenario@example.invalid");
        yield* git("config", "core.hooksPath", ".git/hooks");
        yield* fs.writeFileString(`${project}/notes`, "baseline\n");
        yield* fs.writeFileString(`${project}/selected`, "baseline\n");
        yield* git("add", "--", "notes", "selected");
        yield* git("commit", "-m", "Initial");
        yield* fs.writeFileString(`${project}/selected`, "original staged content\n");
        yield* git("add", "--", "selected");
        yield* fs.writeFileString(`${project}/selected`, "working copy for attempted commit\n");
        yield* run("mkfifo", [`${project}/.git/proof-barrier`]);
        const hook = `${project}/.git/hooks/pre-commit`;
        yield* fs.writeFileString(
          hook,
          "#!/bin/sh\necho ready > .git/proof-ready\nread answer < .git/proof-barrier\nexit 1\n",
        );
        yield* fs.chmod(hook, 0o755);
      }),
    );

    await t3.open(thread);
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
    await screen.getByRole("button", "Open selected in editor").waitFor();
    await screen.getByPlaceholder("Leave empty to auto-generate").fill("Commit everything");
    await screen.getByRole("button", "Commit", { exact: true }).tap();

    // The second terminal: stage notes while the pre-commit check is still running.
    const stagedWhileRunning = await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        while (!(yield* fs.exists(`${project}/.git/proof-ready`))) {
          yield* Effect.sleep("100 millis");
        }
        yield* fs.writeFileString(`${project}/notes`, "separately staged while checks ran\n");
        yield* git("add", "--", "notes");
        const staged = yield* git("show", ":notes");
        yield* fs.writeFileString(`${project}/notes`, "still editing\n");
        yield* fs.writeFileString(`${project}/.git/proof-barrier`, "reject\n");
        return staged;
      }),
    );
    console.error(`[repro] :notes during hook = ${JSON.stringify(stagedWhileRunning)}`);

    await screen.getByText("Action failed", { exact: true }).waitFor();
    await screen.getByRole("button", "Dismiss notification", { exact: true }).tap();
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const terminal = screen.getByLabel("Terminal input");
    await terminal.focus();
    await browser.keyboard.type("export GIT_PAGER=cat; unset PROMPT_COMMAND; unset precmd_functions; PS1='$ '; PROMPT='$ '; clear; printf '\\nAfter rejected commit-all\\nStaged notes:\\n'; git show :notes; printf '\\nStaged selected:\\n'; git show :selected; printf '\\nWorking notes: '; cat notes; printf '\\nHEAD:\\n'; git log -1 --format=%s; touch .git/display-ready");
    await browser.keyboard.press("Enter");
    await runPromise(Effect.gen(function* () {
      const fs = yield* FileSystem.FileSystem;
      while (!(yield* fs.exists(`${project}/.git/display-ready`))) {
        yield* Effect.sleep("100 millis");
      }
    }));
    await app.screenshot("after-rejected-commit-all");
    const after = await runPromise(
      Effect.all({
        notesIndex: git("show", ":notes"),
        selectedIndex: git("show", ":selected"),
        log: git("log", "--oneline"),
      }),
    );
    console.error(`[repro] after rejection ${JSON.stringify(after)}`);
    expect(after.notesIndex.stdout.trim()).toBe("separately staged while checks ran");
  },
);
