import { expect } from "e2e";
import { nativeRecorder } from "./native-proof-recording.ts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";

import { MOBILE, MOBILE_T3_HOME as T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise } from "./t3.ts";
import { test, IOS } from "./t3-mobile.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", { ...IOS, video: "off" }, async ({ t3, app, screen, device }) => {
  const source = await t3.project("Source checkout", repository);
  const origin = `http://127.0.0.1:${MOBILE.serverPort}`;
  const server = startSecondServer(origin);
  let recording = false;
  const recorder = nativeRecorder();
  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();
    await screen.getByText("Requested move", {exact: false}).first().waitFor({timeout:120_000});
    await screen.getByText("Requested move", {exact: false}).first().tap();
    await screen.getByText("Move this thread to another machine?", {exact: true}).waitFor({timeout: 120_000});
    await screen.swipe({from:{x:201,y:650},to:{x:201,y:450},duration:500});
    await recorder.start("move-request");
    recording = true;
    await screen.getByText("Destination machine", {exact: true}).tap();
    await screen.swipe({from:{x:201,y:650},to:{x:201,y:450},duration:500});
    await app.screenshot("move-destination-project");
    await expect(screen.getByText("Choose a project", {exact: true})).toBeVisible();
    await screen.swipe({from:{x:201,y:650},to:{x:201,y:500},duration:500});
    await app.screenshot("available-checkouts");
    await screen.getByText("Second checkout", {exact: true}).tap();
    await screen.swipe({from:{x:201,y:650},to:{x:201,y:350},duration:500});
    await app.screenshot("selected-checkout");
    await screen.getByRole("button", "Move", {exact:true}).tap();
    await screen.getByText("This thread continues on Destination machine", {exact:true}).waitFor({timeout:60_000});
    await app.screenshot("move-completed");
    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 {
    try {
      if (recording) await recorder.stop();
    } finally {
      try {
        await device.closeApp();
      } finally {
        await server.stop();
      }
    }
  }
});
