import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeWS from "@effect/platform-node/NodeWS";
import {
  CommandId,
  ORCHESTRATION_PROTOCOL_VERSION,
  ThreadId,
  WsRpcGroup,
} from "@t3tools/contracts";
import { expect } from "e2e";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { Socket } from "effect/socket";

import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

// A shell keeps an environment's 25 newest settled threads; older ones come from search.
const NEWER_SETTLED = 25;

/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */
const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) {
  const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]);
  const { ticket } = yield* HttpClient.execute(
    HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe(
      HttpClientRequest.bearerToken(issued.stdout.trim()),
    ),
  ).pipe(
    Effect.flatMap(HttpClientResponse.filterStatusOk),
    Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
    Effect.provide(FetchHttpClient.layer),
  );
  // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
  const protocol = yield* Layer.build(
    RpcClient.layerProtocolSocket().pipe(
      Layer.provide(
        Socket.layerWebSocket(
          `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,
        ),
      ),
      Layer.provide(RpcSerialization.layerJson),
      Layer.provide(NodeWS.layerWebSocketConstructor),
    ),
  );
  return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
});

const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4());
const decodePairing = Schema.decodeEffect(
  Schema.fromJsonString(Schema.Struct({ credential: Schema.String })),
);

const settle = Effect.fn("scenario.settle")(
  function* (home: string, origin: string, threadIds: ReadonlyArray<string>) {
    const client = yield* rpcClient(home, origin);
    for (const threadId of threadIds) {
      yield* client["orchestration.dispatchCommand"]({
        type: "thread.settle",
        commandId: CommandId.make(yield* uuid),
        threadId: ThreadId.make(threadId),
      });
    }
  },
  Effect.scoped,
  Effect.provide(NodeCrypto.layer),
);

/** Turns the Linked environments beta on for both servers and links the first to the second. */
const linkEnvironments = Effect.fn("scenario.linkEnvironments")(function* (
  primaryOrigin: string,
  secondOrigin: string,
) {
  const primary = yield* rpcClient(T3_HOME, primaryOrigin);
  const second = yield* rpcClient(SECOND_HOME, secondOrigin);
  for (const client of [primary, second]) {
    yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
  }
  const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]);
  const { credential } = yield* decodePairing(pairing.stdout);
  yield* primary["peerLinks.link"]({
    url: secondOrigin,
    pairingCode: credential,
    access: "full-access",
  });
}, Effect.scoped);


async function mcp(origin: string) {
  const issued = await runPromise(makeState(T3_HOME).cli([
    "auth", "session", "issue", "--subject", "mcp-client", "--token-only",
  ]));
  let session: string | null = null;
  let id = 0;
  async function send(method: string, params?: object) {
    const response = await fetch(`${origin}/mcp`, {
      method: "POST",
      headers: {
        "content-type": "application/json", accept: "application/json, text/event-stream",
        authorization: `Bearer ${issued.stdout.trim()}`,
        ...(session ? { "mcp-session-id": session } : {}),
      },
      body: JSON.stringify({ jsonrpc: "2.0", ...(method.startsWith("notifications/") ? {} : { id: ++id }), method, params }),
    });
    session = response.headers.get("mcp-session-id") ?? session;
    const text = await response.text();
    if (!response.ok) throw new Error(`MCP ${response.status}: ${text}`);
    if (!text.trim()) return null;
    const result = JSON.parse(text.startsWith("data:") || text.startsWith("event:")
      ? text.split("\n").filter(line => line.startsWith("data:")).map(line => line.slice(5).trim()).join("") : text);
    if (result.error || result.result?.isError) throw new Error(JSON.stringify(result));
    return result.result;
  }
  await send("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "scenario", version: "1" } });
  await send("notifications/initialized");
  return async (name: string, args: object) => {
    const result = await send("tools/call", { name, arguments: args });
    return result.structuredContent ?? JSON.parse(result.content.find((c: { type: string }) => c.type === "text").text);
  };
}

test("Opening a linked delegated task selects the delegating parent's sidebar row", WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("Delegation demo");
    const parent = await t3.thread({ project, title: "Delegating parent", messages: ["Prepare delegated work"] });
    const server = startSecondServer(app.baseUrl ?? "");
    try {
      const { host, token } = await server.ready;
      await runPromise(linkEnvironments(app.baseUrl ?? "", host));
      await makeState(SECOND_HOME).state.project("Task workspace");
      const primaryEnvironment = await (await fetch(`${app.baseUrl}/.well-known/t3/environment`)).json();
      const remoteEnvironment = await (await fetch(`${host}/.well-known/t3/environment`)).json();
      const call = await mcp(app.baseUrl ?? "");
      const projects = await call("t3_project_list", { environmentId: remoteEnvironment.environmentId });
      const child = await call("t3_thread_launch", {
        environmentId: remoteEnvironment.environmentId,
        projectId: projects.projects[0].id,
        title: "Delegated sleeper",
        modelSelection: { instanceId: "devReplay", model: "multi-turn" },
        runtimeMode: "approval-required",
        delegatedFrom: { environmentId: primaryEnvironment.environmentId, threadId: parent.threadId, title: "Delegating parent" },
        message: "Wait for further instructions",
      });
      const childLink = `t3-thread://v2/${remoteEnvironment.environmentId}/${child.threadId}`;
      await runPromise(makeState(T3_HOME).cli(["thread", "send", parent.threadId,
        `Open the delegated task: [Delegated sleeper](${childLink})`, "--wait", "--json"]));
      await t3.open("/settings/connections");
      await screen.getByRole("button", "Add environment").tap();
      const dialog = screen.getByRole("dialog");
      await dialog.getByPlaceholder("backend.example.com").fill(host);
      await dialog.getByPlaceholder("PAIRCODE").fill(token);
      await dialog.getByRole("button", "Add environment").tap();
      await screen.getByRole("button", "More actions for Scenario").waitFor({ state: "visible", timeout: 60000 });
      await t3.open(parent);
      await browser.locator('[data-sidebar-row][aria-current="page"]').waitFor({ state: "visible" });
      await screen.getByRole("button", "Delegated sleeper", { exact: false }).tap();
      await screen.getByRole("link", "Thread, Delegated sleeper").waitFor({ state: "visible" });
      await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden" });
      await app.screenshot("parent-open");
      await screen.getByRole("link", "Thread, Delegated sleeper").tap();
      await browser.locator('[aria-current="page"]').filter({ hasText: "Delegated sleeper" }).waitFor({ state: "visible", timeout: 60000 });
      await screen.getByRole("textbox").waitFor({ state: "visible" });
      await screen.getByText("Wait for further instructions", { exact: false }).first().waitFor({ state: "visible" });
      await screen.getByText("first fixture turn complete", { exact: false }).waitFor({ state: "visible" });
      await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden" });
      await app.screenshot("delegated-task-open");
      await expect(browser.locator('[data-sidebar-row][aria-current="page"]').filter({ hasText: "Delegating parent" })).toBeVisible();
    } finally {
      await server.stop();
    }
  });
