import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";

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

test(
  "A confirmed push checks for commits on the branch it names",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("demo");
    const remote = `${project}/../remote.git`;
    const realGit = (await runPromise(run("sh", ["-c", "command -v git"]))).stdout.trim();
    const git = async (...args: string[]) =>
      (await runPromise(run(realGit, args, { cwd: project }))).stdout.trim();
    await git("init", "--bare", "--initial-branch=main", remote);
    await git("remote", "add", "origin", remote);
    await git("push", "-u", "origin", "main");
    await git("remote", "set-head", "origin", "main");
    await git("switch", "-c", "feature");
    await git("push", "-u", "origin", "feature");
    await git("switch", "main");
    await git(
      "-c",
      "user.name=Scenario",
      "-c",
      "user.email=scenario@example.invalid",
      "commit",
      "--allow-empty",
      "-m",
      "Main work",
    );

    const input = { project, title: "Push work", messages: ["Start"] };
    const thread = await t3.thread({ ...input, model: "default" }).catch((error: unknown) => {
      if (!String(error).includes("Model default is not advertised by provider devReplay."))
        throw error;
      return t3.thread(input);
    });
    await t3.open(thread);
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Push", { exact: true }).tap();
    const confirm = screen.getByRole("button", "Push to main", { exact: true });
    await confirm.waitFor();

    // Keep the checkout as main until the push has read its name and is about to count commits.
    const wrapper = writeFakeCli({
      directory: `${T3_HOME}/bin`,
      name: "git",
      source: `
      import { spawnSync } from "node:child_process";
      import { unlinkSync } from "node:fs";
      const git = ${JSON.stringify(realGit)};
      const args = process.argv.slice(2);
      if (process.cwd() === ${JSON.stringify(project)} && args.slice(0, 3).join(" ") === "rev-list --left-right --count") {
        unlinkSync(${JSON.stringify(`${T3_HOME}/bin/git`)});
        const moved = spawnSync(git, ["switch", "--quiet", "feature"], { stdio: "inherit" });
        if (moved.status !== 0) process.exit(1);
      }
      process.exit(spawnSync(git, args, { stdio: "inherit" }).status ?? 1);
    `,
    });
    try {
      await confirm.tap();
      // The agent's reply also shows "Done", so read the push's own result.
      await browser
        .locator('[role="group"][aria-label="Git actions for demo"], [data-slot="toast-title"]')
        .getByText(/^Done$|^Action failed$|^Pushed /)
        .waitFor();
      await app.screenshot("push-after-checkout-moves-during-branch-status");
      expect(await git("branch", "--show-current")).toBe("feature");
      if (await screen.getByText(/main is no longer checked out/).isVisible()) return;
      expect(await git("--git-dir", remote, "log", "-1", "--format=%s", "main")).toBe("Main work");
    } finally {
      await runPromise(
        Effect.flatMap(FileSystem.FileSystem, (fs) => fs.remove(wrapper, { force: true })),
      );
    }
  },
);
