/// <reference lib="dom" />
import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const decode = Schema.decodeEffect(
  Schema.fromJsonString(Schema.Struct({ credential: Schema.String })),
);
const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));
const mode = process.env.PROOF_PATH ?? "chat";

test(
  "An externally linked environment resolves without a reload",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const origin = app.baseUrl ?? "";
    const project = await t3.project("Link proof");
    const server = startSecondServer(origin);
    const transcript = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
    const original = await readFile(transcript, "utf8");
    try {
      const { host } = await server.ready;
      await runPromise(
        Effect.gen(function* () {
          for (const [home, url] of [
            [T3_HOME, origin],
            [SECOND_HOME, host],
          ]) {
            const client = yield* rpcClient(home!, url!);
            yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
          }
        }).pipe(Effect.scoped),
      );
      const remote = makeState(SECOND_HOME);
      const remoteProject = await remote.state.project("Remote notes");
      const child = JSON.parse(
        (
          await runPromise(
            remote.cli([
              "thread",
              "start",
              remoteProject,
              "Read these remote design notes",
              "--title",
              "Remote design notes",
              "--provider",
              "devReplay",
              "--model",
              "multi-turn",
              "--json",
            ]),
          )
        ).stdout,
      );
      const via = await runPromise(environmentId(origin));
      const linked = await runPromise(environmentId(host));
      const turn = (text: string) => [
        { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
        {
          type: "emit_inbound",
          frame: {
            kind: "notification",
            method: "session/update",
            params: {
              sessionId: "dev-replay-session",
              update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
            },
          },
        },
        {
          type: "emit_inbound",
          frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } },
        },
      ];
      await writeFile(
        transcript,
        [
          ...turn("Ready for the remote thread."),
          ...turn(
            mode === "chat"
              ? `Delegated: [Thread on B](t3-thread://v2/${linked}/${child.threadId})`
              : "Remote task noted.",
          ),
        ]
          .map((e) => JSON.stringify(e))
          .join("\n") + "\n",
      );
      const parent = JSON.parse(
        (
          await runPromise(
            makeState(T3_HOME).cli([
              "thread",
              "start",
              project,
              "Prepare the conversation",
              "--title",
              "Current conversation",
              "--provider",
              "devReplay",
              "--model",
              "showcase",
              "--json",
            ]),
          )
        ).stdout,
      );
      await t3.open(parent);
      await screen.getByText("Ready for the remote thread.", { exact: true }).waitFor();
      await pause(1500); // Composer's linked-environment names have loaded before the external link.
      await runPromise(
        Effect.gen(function* () {
          const pairing = yield* remote.cli(["auth", "pairing", "create", "--json"]);
          const { credential } = yield* decode(pairing.stdout);
          const primary = yield* rpcClient(T3_HOME, origin);
          yield* primary["peerLinks.link"]({
            url: host,
            pairingCode: credential,
            access: "full-access",
          });
        }).pipe(Effect.scoped),
      );
      await pause(15000); // Match the report: beyond names' ten-second staleTime, without reload.
      if (mode === "direct") {
        await browser.evaluate((path) => {
          history.pushState({}, "", path);
          window.dispatchEvent(new PopStateEvent("popstate"));
        }, `/linked/${via}/${linked}/${child.threadId}`);
        await pause(2500);
        await app.screenshot("direct-linked-route");
        await expect(screen.getByText("On Scenario via Scenario", { exact: true })).toBeVisible();
      } else {
        await runPromise(
          makeState(T3_HOME).cli([
            "thread",
            "send",
            parent.threadId,
            "Show the delegated thread",
            "--json",
          ]),
        );
        await screen.getByText("Delegated:", { exact: false }).waitFor();
        await pause(3000);
        await app.screenshot("newly-linked-thread-chip");
        await expect(
          screen.getByRole("button", "Thread, Thread on B", { exact: true }),
        ).toBeVisible();
        await screen.getByRole("button", "Thread, Thread on B", { exact: true }).hover();
        await expect(
          screen.getByText("Read the thread on Scenario", { exact: true }),
        ).toBeVisible();
        await pause(800);
        await app.screenshot("linked-thread-tooltip");
        await screen.getByRole("button", "Thread, Thread on B", { exact: true }).tap();
        await screen.getByText("Read these remote design notes", { exact: true }).waitFor();
        await pause(800);
        await app.screenshot("linked-thread-read-only");
      }
    } finally {
      await pause(2000);
      await writeFile(transcript, original);
      await server.stop();
    }
  },
);
