import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Stream from "effect/Stream";

import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test(
  "Committing on a new branch leaves a running thread's checkout alone",
  WEB,
  async ({ t3, app, screen }) => {
    const project = await t3.project("demo");
    const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
    await git("config", "user.name", "Scenario");
    await git("config", "user.email", "scenario@example.invalid");

    await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl);
        yield* client.subscribeServerConfig({}).pipe(
          Stream.filter((event) => {
            const providers =
              event.type === "snapshot"
                ? event.config.providers
                : event.type === "providerStatuses"
                  ? event.payload.providers
                  : [];
            const replay = providers.find((provider) => provider.instanceId === "devReplay");
            return ["multi-turn", "question"].every((slug) =>
              replay?.models.some((model) => model.slug === slug),
            );
          }),
          Stream.runHead,
        );
      }).pipe(Effect.scoped, Effect.timeout("30 seconds")),
    );

    const idle = await t3.thread({
      project,
      title: "Commit here",
      messages: ["Start"],
    });
    const running = await t3.thread({
      project,
      title: "Waiting for input",
      messages: ["Ask me a question"],
      model: "question",
    });
    await t3.open(running);
    await screen.getByRole("button", "Stop generation").waitFor();
    await runPromise(
      Effect.flatMap(FileSystem.FileSystem, (fs) =>
        fs.writeFileString(`${project}/README.md`, "A local edit\n"),
      ),
    );

    await t3.open(idle);
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
    await screen.getByPlaceholder("Leave empty to auto-generate").fill("Add local notes");
    await screen.getByRole("button", "Commit on new branch", { exact: true }).tap();
    await screen.getByText(/^Committed [0-9a-f]+$|^Action failed$/).waitFor();
    await app.screenshot("checkout-after-feature-commit");
    expect((await git("branch", "--show-current")).stdout.trim()).toBe("main");
    await screen.getByText(/'Waiting for input' is still working in this checkout/).waitFor();
  },
);
