// Scratch driver for issue 38660. Not committed.
// usage: node scratch-38660-driver.ts seed <home> <origin> <projectId> <settledCount> <idleUnsettledCount>
//        node scratch-38660-driver.ts measure <home> <runs>
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeWS from "@effect/platform-node/NodeWS";
import {
  CommandId,
  ORCHESTRATION_PROTOCOL_VERSION,
  ProjectId,
  ThreadId,
  WsRpcGroup,
} from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
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 EnvironmentAuth from "./src/auth/EnvironmentAuth.ts";
import * as ServerConfig from "./src/config.ts";
import { mcpToolSession } from "./src/mcp/AcpMcpStdioBridge.ts";
import { readLiveServerRuntimeState } from "./src/serverRuntimeState.ts";
import { resolveCliAuthConfig } from "./src/cli/config.ts";

const [mode, home, ...rest] = process.argv.slice(2);

const withAuth = <A, E, R>(
  run: (auth: EnvironmentAuth.EnvironmentAuth["Service"], origin: string) => Effect.Effect<A, E, R>,
) =>
  Effect.gen(function* () {
    const config = yield* resolveCliAuthConfig(
      { baseDir: Option.some(home!), json: true } as never,
      Option.none(),
      { quietLogs: true },
    );
    return yield* Effect.gen(function* () {
      const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
      const origin = Option.getOrThrow(runtimeState).origin;
      const auth = yield* EnvironmentAuth.EnvironmentAuth;
      return yield* run(auth, origin);
    }).pipe(
      Effect.provide(
        EnvironmentAuth.layerRuntime.pipe(
          Layer.provide(ServerConfig.layer(config)),
          Layer.provide(Layer.succeed(References.MinimumLogLevel, "Error")),
        ),
      ),
    );
  });

const seed = Effect.gen(function* () {
  const [projectId, settledCountRaw, idleCountRaw] = rest;
  const settledCount = Number(settledCountRaw);
  const idleCount = Number(idleCountRaw);
  yield* withAuth((auth, origin) =>
    Effect.gen(function* () {
      const issued = yield* auth.issueSession({ label: "scratch-38660" } as never);
      const { ticket } = yield* HttpClient.execute(
        HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe(
          HttpClientRequest.bearerToken(issued.token),
        ),
      ).pipe(
        Effect.flatMap(HttpClientResponse.filterStatusOk),
        Effect.flatMap(
          HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String })),
        ),
        Effect.provide(FetchHttpClient.layer),
      );
      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),
        ),
      );
      const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
      const total = settledCount + idleCount;
      const started = Date.now();
      yield* Effect.forEach(
        Array.from({ length: total }, (_, index) => index),
        (index) =>
          Effect.gen(function* () {
            const threadId = ThreadId.make(`scratch-${started}-${index}`);
            yield* client["orchestration.dispatchCommand"]({
              type: "thread.create",
              commandId: CommandId.make(crypto.randomUUID()),
              createdBy: "user",
              creationSource: "web",
              threadId,
              projectId: ProjectId.make(projectId!),
              title: `Synthetic thread ${started}-${index}`,
              modelSelection: { instanceId: "devReplay", model: "question" },
              runtimeMode: "full-access",
              interactionMode: "default",
              branch: null,
              worktreePath: null,
            } as never);
            if (index < settledCount) {
              yield* client["orchestration.dispatchCommand"]({
                type: "thread.settle",
                commandId: CommandId.make(crypto.randomUUID()),
                threadId,
              } as never);
            }
            if (index % 500 === 0) console.error(`seeded ${index}/${total} ${Date.now() - started}ms`);
          }),
        { concurrency: 8, discard: true },
      );
      console.error(`seeded ${total} in ${Date.now() - started}ms`);
    }).pipe(Effect.scoped),
  );
});

const measure = Effect.gen(function* () {
  const runs = Number(rest[0] ?? 10);
  yield* withAuth((auth, origin) =>
    Effect.gen(function* () {
      const issued = yield* Effect.acquireRelease(
        auth.issueMcpClientSession({
          label: "scratch-38660",
          access: "full-access",
          peerLink: false,
          client: { deviceType: "bot" },
        }),
        (session) => auth.revokeSession(session.sessionId).pipe(Effect.ignore),
      );
      const session = yield* mcpToolSession({
        endpoint: new URL("/mcp", origin).href,
        authorization: `Bearer ${issued.token}`,
        clientName: "scratch-38660",
      });
      const live = ["preparing", "queued", "starting", "running", "waiting"];
      const cases: Record<string, Record<string, unknown>> = {
        "live statuses": { allProjects: true, includeSubagents: true, statuses: live, limit: 1 },
        "live statuses + settled:false": {
          allProjects: true,
          includeSubagents: true,
          statuses: live,
          settled: false,
          limit: 1,
        },
        "no filter (baseline)": { allProjects: true, includeSubagents: true, limit: 1 },
      };
      const results: Record<string, { ms: Array<number>; total: unknown }> = {};
      for (const [name, args] of Object.entries(cases)) {
        // one warm-up call
        yield* session.call("t3_thread_list", args);
        const ms: Array<number> = [];
        let total: unknown;
        for (let i = 0; i < runs; i++) {
          const t0 = performance.now();
          const raw = (yield* session.call("t3_thread_list", args)) as {
            structuredContent?: { total?: number };
            isError?: boolean;
          };
          ms.push(Math.round(performance.now() - t0));
          if (raw.isError) throw new Error(JSON.stringify(raw));
          total = raw.structuredContent?.total;
        }
        results[name] = { ms, total };
      }
      for (const [name, { ms, total }] of Object.entries(results)) {
        const sorted = [...ms].sort((a, b) => a - b);
        const median = sorted[Math.floor(sorted.length / 2)];
        console.log(
          `${name.padEnd(32)} total=${String(total).padEnd(4)} median=${median}ms min=${sorted[0]}ms max=${sorted.at(-1)}ms runs=${JSON.stringify(ms)}`,
        );
      }
    }).pipe(Effect.scoped),
  );
});

await Effect.runPromise(
  (mode === "seed" ? seed : measure).pipe(
    Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)),
  ) as Effect.Effect<void>,
);
process.exit(0);
