/// <reference lib="dom" />
import { watch } from "node:fs";
import { access, writeFile, chmod } from "node:fs/promises";
import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Rejected selected-file commit preserves the staged version", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("selected-commit", { "a.txt": "original a\n", "b.txt": "original b\n" });
  const git = async (...args: string[]) => (await runPromise(run("git", args, { cwd: project }))).stdout.trimEnd();
  await git("config", "user.name", "Scenario");
  await git("config", "user.email", "scenario@example.invalid");
  const thread = await t3.thread({ project, title: "Rejected selected-file commit", messages: ["Start"] });
  const originalHead = await git("rev-parse", "HEAD");
  await writeFile(`${project}/a.txt`, "staged only\n");
  await git("add", "a.txt");
  await writeFile(`${project}/a.txt`, "unstaged only\n");
  await writeFile(`${project}/b.txt`, "excluded change\n");
  await writeFile(`${project}/.git/hooks/pre-commit`, "#!/bin/sh\necho 'Commit rejected by hook' >&2\nexit 1\n");
  await chmod(`${project}/.git/hooks/pre-commit`, 0o755);
  await git("config", "core.hooksPath", ".git/hooks");
  await t3.open(thread);
  // Hide error details containing local paths from public evidence.
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.textContent = '[data-slot="toast-description"] { visibility: hidden !important; }';
    document.head.append(style);
    return null;
  });
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]').waitFor();
  const terminalReport = async (phase: string) => {
    const marker = `.git/evidence-${phase}`;
    const completed = new Promise<void>((resolve) => {
      const watcher = watch(`${project}/.git`, async () => {
        try { await access(`${project}/${marker}`); watcher.close(); resolve(); } catch {}
      });
    });
    await input.focus();
    await browser.keyboard.type(`PS1='$ '; clear; printf '${phase}: selected a.txt, excluded b.txt\\nINDEX a.txt: '; git --no-pager show :a.txt; printf 'WORKTREE a.txt: '; cat a.txt; printf 'STATUS:\\n'; git status --short; touch ${marker}\n`);
    await completed;
  };
  await terminalReport("Before");
  await app.screenshot("before-rejected-commit");
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  await screen.getByRole("button", "Git action options").tap();
  await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
  await screen.getByRole("button", "Edit", { exact: true }).tap();
  await screen.getByRole("checkbox", "Include b.txt").tap();
  await screen.getByRole("button", "Open b.txt in editor").getByText("Excluded").waitFor();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill("Rejected");
  await app.screenshot("selected-file-commit");
  await screen.getByRole("button", "Commit", { exact: true }).tap();
  await screen.getByText("Action failed", { exact: true }).waitFor();
  await app.screenshot("hook-rejected-commit");
  await screen.getByRole("button", "Dismiss notification", { exact: true }).tap();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  await terminalReport("After");
  await app.screenshot("index-after-rejected-commit");
  expect(await git("show", ":a.txt")).toBe("staged only");
  expect(await git("rev-parse", "HEAD")).toBe(originalHead);
});
