import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeWS from "@effect/platform-node/NodeWS";
import { CommandId, ThreadId, ORCHESTRATION_PROTOCOL_VERSION, WsRpcGroup } from "@t3tools/contracts";
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 * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";
/** 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 delegate = Effect.fn("scenario.delegate")(function* (origin: string, threadId: string) {
  const client = yield* rpcClient(T3_HOME, origin);
  const projection = yield* client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(threadId) });
  const run = projection.runs.at(-1)!;
  yield* client["orchestration.dispatchCommand"]({
    type: "delegated_task.request", createdBy: "agent", creationSource: "mcp", commandId: CommandId.make(crypto.randomUUID()),
    parentThreadId: ThreadId.make(threadId), parentRunId: run.id, parentNodeId: run.rootNodeId!,
    task: "Review refactor diffs and wait for approval before changing files.", title: "Review refactor diffs",
    modelSelection: { instanceId: "devReplay", model: "approval" },
    runtimeMode: "approval-required", interactionMode: "default",
  });
}, Effect.scoped);

test("A background subagent has the same Waiting status in the line and details", WEB, async ({ t3, app, screen }) => {
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  await fs.writeFile(settingsPath, JSON.stringify({ ...settings, defaultRuntimeMode: "approval-required" }));
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Background review", model: "approval", messages: ["Launch Review refactor diffs in the background and end the parent turn."] });
  await runPromise(delegate(app.baseUrl!, thread.threadId));
  await t3.open(thread);
  await screen.getByRole("region", "Conversation", { exact: true }).getByRole("button", "Approve", { exact: true }).tap();
  await screen.getByText("Waiting · Review refactor diffs", { exact: true }).waitFor({ state: "visible" });
  await app.screenshot("background-line");
  await screen.getByRole("button", "Details", { exact: true }).tap();
  await screen.getByRole("dialog").waitFor({ state: "visible" });
  await app.screenshot("background-details");
  await expect(screen.getByRole("dialog").getByText("Waiting", { exact: true })).toBeVisible();
});
