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

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

const decodePairing = Schema.decodeEffect(
  Schema.fromJsonString(Schema.Struct({ credential: Schema.String })),
);

const repository = {
  ".git/config": '[remote "origin"]\nurl = https://github.com/scenario/branch-preservation.git\n',
};

test("Moving a thread preserves a trailing nonbreaking space in its branch", WEB, async ({ t3, app, screen }) => {
  const source = await t3.project("Source checkout", repository);
  const origin = app.baseUrl ?? "";
  const server = startSecondServer(origin);
  try {
    const { host } = await server.ready;
    const remote = makeState(SECOND_HOME);
    const second = await remote.state.project("Second checkout", repository);
    await runPromise(
      Effect.gen(function* () {
        yield* run("git", ["fetch", "-u", source, "+main:main"], { cwd: second });
        yield* run("git", ["reset", "--hard", "main"], { cwd: second });
        yield* run("git", ["checkout", "-b", "topic"], { cwd: second });
        yield* run("git", ["checkout", "-b", "topic\u00a0"], { cwd: source });
        const primary = yield* rpcClient(T3_HOME, origin);
        const destination = yield* rpcClient(SECOND_HOME, host);
        for (const client of [primary, destination]) {
          yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
        }
        const pairing = yield* remote.cli(["auth", "pairing", "create", "--json"]);
        const { credential } = yield* decodePairing(pairing.stdout);
        yield* primary["peerLinks.link"]({
          url: host,
          pairingCode: credential,
          access: "full-access",
        });
      }).pipe(Effect.scoped),
    );

    await t3.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((await server.ready).token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("heading", "Environments", { exact: true }).waitFor();
    const thread = await t3.thread({
      project: source,
      title: "Ready to move",
      messages: ["Start"],
      model: "showcase",
    });
    await t3.open(thread);
    await screen.getByRole("button", "Thread actions for Ready to move").tap();
    await screen.getByRole("menuitem", "Continue on another machine…").tap();
    await screen.getByRole("button", /^Move to /).tap();
    await screen.getByText("From T3 Code · Scenario", { exact: true }).waitFor({ timeout: 60_000 });
    const moved = await runPromise(
      Effect.gen(function* () {
        const destination = yield* rpcClient(SECOND_HOME, host);
        const item = yield* destination["orchestration.subscribeShell"]({}).pipe(Stream.runHead);
        if (item._tag !== "Some" || item.value.kind !== "snapshot") throw Error("No snapshot");
        const moved = item.value.snapshot.threads.find(({ title }) => title === "Ready to move");
        if (!moved) throw Error("Moved thread missing");
        return moved;
      }).pipe(Effect.scoped),
    );
    const target = await runPromise(environmentId(host));
    await t3.open(`/${target}/${moved.id}`);
    await screen.getByRole("heading", "Ready to move").waitFor();
    await screen.getByRole("combobox", /Branch:|Select ref/).first().waitFor({ timeout: 60_000 });
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 60_000 });
    await app.screenshot("moved-thread-branch");
    const actual = await runPromise(run("git", ["symbolic-ref", "--quiet", "HEAD"], {
      cwd: moved.worktreePath ?? second, allowExit: [0, 1],
    }));
    expect(actual.stdout.replace(/\n$/, "")).toBe("refs/heads/topic\u00a0");
  } finally {
    await server.stop();
  }
});
