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

import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test(
  "Automatic routing keeps a base branch just created on the destination machine",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const repository = {
      ".git/config": '[remote "origin"]\n\turl = https://github.com/scenario/demo.git\n',
      "t3.json": JSON.stringify({ defaultThreadEnvMode: "worktree" }),
    };
    await t3.project("demo", repository);
    const configure = (home: string, origin: string) =>
      runPromise(
        Effect.scoped(
          Effect.gen(function* () {
            const client = yield* rpcClient(home, origin);
            yield* client["server.updateSettings"]({
              patch: {
                newWorktreesStartFromOrigin: false,
                automaticGitFetchInterval: Duration.zero,
              },
            });
          }),
        ),
      );
    await configure(T3_HOME, app.baseUrl ?? "");
    const second = makeState(SECOND_HOME);
    const server = startSecondServer(app.baseUrl ?? "");
    try {
      const { host, token } = await server.ready;
      await configure(SECOND_HOME, host);
      const destination = await second.state.project("demo", repository);
      const git = (...args: string[]) => runPromise(run("git", args, { cwd: destination }));
      await git("branch", "-m", "destination-base");
      await git(
        "-c",
        "user.name=Scenario",
        "-c",
        "user.email=scenario@example.invalid",
        "commit",
        "--quiet",
        "--allow-empty",
        "-m",
        "Destination diverged",
      );
      await runPromise(
        Effect.scoped(
          Effect.gen(function* () {
            const client = yield* rpcClient(SECOND_HOME, host);
            const refs = yield* client["vcs.listRefs"]({ cwd: destination });
            if (!refs.refs.some((ref) => ref.name === "destination-base")) {
              throw new Error("The destination checkout was missing from the initial snapshot.");
            }
          }),
        ),
      );

      await t3.open();
      await screen
        .getByRole("combobox", /^Branch: (From )?main/)
        .first()
        .waitFor();
      const draftPath = new URL(await browser.url()).pathname;
      await app.open("/settings/connections");
      await screen.getByRole("button", "Add environment").tap();
      const dialog = screen.getByRole("dialog");
      await dialog.getByPlaceholder("backend.example.com").fill(host);
      await dialog.getByPlaceholder("PAIRCODE").fill(token);
      await dialog.getByRole("button", "Add environment").tap();

      await screen.getByRole("switch", "Automatically balance load").tap();
      await screen.getByRole("button", /^Load balancing/).tap();
      const preferences = screen.getByRole("combobox", "Scenario load preference");
      const setPreference = async (side: "first" | "last", value: string) => {
        await preferences[side]().tap();
        await screen.getByRole("option", value, { exact: true }).tap();
      };
      await setPreference("last", "Manual only");

      await app.open(draftPath);
      await screen
        .getByRole("combobox", "Run on")
        .getByText("Auto balance", { exact: true })
        .waitFor();
      await screen
        .getByRole("combobox", /^Branch: (From )?main/)
        .first()
        .waitFor();

      await app.open("/settings/connections");
      await screen.getByRole("button", /^Load balancing/).tap();
      await setPreference("last", "Normal");
      await setPreference("first", "Manual only");
      await git("branch", "main", "HEAD^");

      await app.open(draftPath);
      await screen
        .getByRole("combobox", /^Branch: (From )?main/)
        .first()
        .waitFor();
      await screen.getByRole("combobox", "Workspace").getByText("New worktree").waitFor();
      await screen.getByRole("textbox").fill("Plan the next change");
      await screen.getByRole("button", "Submit message").tap();
      await screen.getByRole("button", /^Changes vs /).waitFor();
      await app.screenshot("worktree-after-automatic-routing");
      const { stdout } = await git("worktree", "list", "--porcelain", "-z");
      const worktree = stdout
        .split("\0")
        .filter((line) => line.startsWith("worktree "))
        .map((line) => line.slice("worktree ".length))
        .find((path) => path !== destination);
      if (!worktree) throw new Error("The destination did not create a worktree.");
      const head = await git("-C", worktree, "log", "-1", "--format=%s");
      expect(head.stdout.trim()).toBe("Initial commit");
    } finally {
      await server.stop();
    }
  },
);
