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("An agent move request can choose between linked checkouts", { ...WEB, video: "off" }, async ({ t3, app, screen, browser }) => {
  const source = await t3.project("Source checkout", repository);
  const origin = app.baseUrl ?? "";
  const server = startSecondServer(origin);
  let recording = false;
  try {
    const { host } = await server.ready;
    const remote = makeState(SECOND_HOME);
    await remote.state.project("First checkout", repository);
    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: "approval-required",
        });
      }).pipe(Effect.scoped),
    );

    const thread = await runPromise(Effect.gen(function* () {
      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: {providerInstances: {opencode: {driver: "opencode", enabled: true}}}});
      }
      const started = yield* makeState(T3_HOME).cli(["thread", "start", source,
        "Call t3_thread_handoff now to ask me to move this thread. Do not ask in chat. Do not specify a project or run any other tools. Set continuationPrompt to: The move is complete. Reply only Move complete. End your turn after calling it.",
        "--provider", "opencode", "--model", "openai/gpt-6-luna", "--title", "Requested move", "--wait", "--json"]);
      return JSON.parse(started.stdout) as {threadId: string};
    }).pipe(Effect.scoped));
    await t3.open(thread);
    await screen.getByText("Move this thread to another machine?", {exact: true}).waitFor({timeout: 120_000});
    await app.startRecording({ name: "move-request" });
    recording = true;
    await screen.getByRole("combobox", "Machine to continue on").tap();
    await screen.getByRole("option", /^Destination machine/).tap();
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1000)));
    await app.screenshot("move-destination-project");
    await expect(screen.getByRole("combobox", "Choose a project")).toBeVisible();
    await screen.getByRole("combobox", "Choose a project").tap();
    await expect(screen.getByRole("option", /^First checkout/)).toBeVisible();
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1000)));
    await app.screenshot("available-checkouts");
    await screen.getByRole("option", /^Second checkout/).tap();
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1000)));
    await app.screenshot("selected-checkout");
    await screen.getByRole("button", "Move", {exact:true}).tap();
    await screen.getByText(/^This thread continues on /).waitFor();
    await screen.getByText("Thread moved from", { exact: false }).waitFor();
    await screen.getByText(/^Move complete[.!]?$/i).waitFor({timeout:120_000});
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1000)));
    await app.screenshot("destination-conversation");
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 2000)));
    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 { projects, threads } = item.value.snapshot;
        const moved = threads.find(({ title }) => title === "Requested move");
        expect(projects.find(({ id }) => id === moved?.projectId)?.workspaceRoot).toBe(second);
      }).pipe(Effect.scoped),
    );
  } finally {
    if (recording) await app.stopRecording();
    await t3.open("/settings/general");
    await server.stop();
  }
});
