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("A directly connected mobile destination lists all 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 remote.state.project("Unrelated project", {".git/config": '[remote "origin"]\nurl = https://example.com/other/repository.git\n'});
    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 t3.thread({
      project: source,
      title: "Ready to move",
      messages: ["Start"],
    });
    await t3.open();
    await screen.getByText("Ready to move", { exact: false }).first().waitFor({ timeout: 120_000 });
    const pairing = await runPromise(remote.cli(["auth", "pairing", "create", "--base-url", host.replace("127.0.0.1", MOBILE.host)]));
    const url = /Pair URL:\s*(\S+)/.exec(`${pairing.stdout}\n${pairing.stderr}`)?.[1];
    if (!url) throw Error("No direct-client pairing URL");
    await device.openLink(`t3code-dev://connections/new?${new URLSearchParams({pairingUrl: url, autoConnect: "1"})}`, {app: "com.t3tools.t3code.dev"});
    await device.alert("accept").catch(() => {});
    await screen.getByLabel("Filter threads by project").tap();
    await screen.getByText("Unrelated project", {exact:false}).waitFor({timeout:60_000});
    await screen.getByText("All projects", {exact:true}).tap();
    await screen.getByText("Ready to move", { exact: false }).first().waitFor({ timeout: 120_000 });
    await recorder.start("native-move");
    recording = true;
    await screen.getByText("Ready to move", { exact: false }).first().longPress();
    await screen.getByText("Continue on another machine", { exact: true }).tap();
    await screen.getByRole("button", /^Destination machine/).waitFor();
    await new Promise((resolve) => setTimeout(resolve, 1000));
    await screen.getByRole("button", /^Destination machine/).tap();
    await screen.getByText(/Several projects there have this repository/).waitFor();
    await app.screenshot("move-destination-project");
    await expect(screen.getByText("Choose a project", { exact: true })).toBeVisible();
    await expect(screen.getByText("First checkout", { exact: true })).toBeVisible();
    await screen.swipe({from:{x:201,y:800},to:{x:201,y:520},duration:500});
    await screen.swipe({from:{x:201,y:800},to:{x:201,y:620},duration:500});
    await expect(screen.getByText("Unrelated project", { exact: true })).toBeVisible();
    await app.screenshot("available-checkouts");
  } finally {
    try {
      if (recording) await recorder.stop();
    } finally {
      try {
        await device.closeApp();
      } finally {
        await server.stop();
      }
    }
  }
});
