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 { 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://example.com/team/repo.git\n',
};

test("A move finishes after the browser disconnects during packaging", 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 });
        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),
    );

    const thread = await t3.thread({
      project: source,
      title: "Move me",
      messages: ["Start"],
    });
    // A compressible untracked file makes real git packaging take long enough to disconnect.
    await runPromise(run("python3", ["-c", "import sys; f=open(sys.argv[1], 'wb'); chunk=b'synthetic checkout data\\n'*43691; [f.write(chunk) for _ in range(512)]; f.close()", `${source}/checkout-data.txt`]));
    await t3.open(thread);
    await screen.getByRole("button", "Thread actions for Move me").tap();
    await screen.getByRole("menuitem", "Continue on another machine…").tap();
    await screen.getByRole("button", /^Move to /).tap();
    await screen.getByText(/^Moving to /).first().waitFor();
    await app.screenshot("packaging-before-disconnect");
    await app.open("about:blank");
    // Give both live servers time to finish; neither is restarted.
    await new Promise((resolve) => setTimeout(resolve, 60000));
    await t3.open(thread);
    try {
      await expect(screen.getByRole("button", "New thread in Second checkout", { exact: true })).toBeVisible();
      await expect(screen.getByText("Thread moved", { exact: true })).toBeVisible();
    } finally {
      await app.screenshot("thread-after-disconnect");
    }
    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 { threads } = item.value.snapshot;
        const moved = threads.find(({ title }) => title === "Move me");
        expect(moved?.title).toBe("Move me");
      }).pipe(Effect.scoped),
    );
  } finally {
    await server.stop();
  }
});
