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("Recorded selected-file commit clears its message despite an index lock", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const git = async (...args: string[]) => (await runPromise(run("git", args, { cwd: project }))).stdout.trimEnd();
  await git("checkout", "-b", "feature/partial");
  await git("config", "user.name", "Scenario");
  await git("config", "user.email", "scenario@example.invalid");
  await git("config", "core.hooksPath", ".git/hooks");
  const start = (model: string) => t3.thread({ project, title: "Selected-file commit", messages: ["Start"], model });
  const thread = await start("multi-turn").catch(error => {
    if (!String(error).includes("Advertised models: default")) throw error;
    return start("default").catch(next => {
      if (!String(next).includes("Model default is not advertised")) throw next;
      return start("multi-turn");
    });
  });
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.writeFileString(`${project}/.git/hooks/post-commit`, '#!/bin/sh\n: > "$(git rev-parse --absolute-git-dir)/index.lock"\n');
    yield* fs.chmod(`${project}/.git/hooks/post-commit`, 0o755);
    yield* fs.writeFileString(`${project}/first.txt`, "First file\n");
    yield* fs.writeFileString(`${project}/later.txt`, "Later file\n");
  }));
  await t3.open(thread);
  const openCommit = async () => {
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
    await screen.getByRole("button", "Open later.txt in editor").waitFor();
  };
  await openCommit();
  await screen.getByRole("button", "Edit", { exact: true }).tap();
  await screen.getByRole("checkbox", "Include later.txt").tap();
  await screen.getByRole("button", "Open later.txt in editor").getByText("Excluded").waitFor();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill("Commit the first file");
  await screen.getByRole("button", "Commit", { exact: true }).tap();
  await screen.getByText(/^(Action failed|Committed [a-f0-9]+)$/).waitFor();
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 600)));
  await app.screenshot("commit-result");
  const recorded = await git("log", "-1", "--format=%s");
  const paths = await git("diff-tree", "--no-commit-id", "-r", "--name-only", "HEAD");
  console.log(JSON.stringify({ recorded, paths }));
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.remove(`${project}/.git/index.lock`)));
  console.log(await git("status", "--porcelain"));
  if (await browser.evaluate(() => !!document.querySelector('button[aria-label="Dismiss notification"]'))) {
    await screen.getByRole("button", "Dismiss notification", { exact: true }).tap();
  }
  await openCommit();
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 600)));
  await app.screenshot("next-commit-message");
  await expect(screen.getByPlaceholder("Leave empty to auto-generate")).toHaveValue("");
});
