// Scratch driver for issue #41504: creates N archived threads in one project over the server's RPC.
// Usage: node seed-archived.ts <origin> <session-token-file> <count> <synthetic-workspace-root>
import * as NodeWS from "@effect/platform-node/NodeWS";
import {
  CommandId,
  ORCHESTRATION_PROTOCOL_HEADER,
  ORCHESTRATION_PROTOCOL_VERSION,
  ProjectId,
  ProviderInstanceId,
  ThreadId,
  WsRpcGroup,
} from "@t3tools/contracts";
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 { randomUUID } from "node:crypto";

const [origin, tokenFile, countText, workspaceRoot] = process.argv.slice(2);
const token = (await (await import("node:fs/promises")).readFile(tokenFile!, "utf8")).trim();
const count = Number(countText);

const program = Effect.gen(function* () {
  const http = (yield* HttpClient.HttpClient).pipe(
    HttpClient.mapRequest((request) =>
      request.pipe(
        HttpClientRequest.bearerToken(token),
        HttpClientRequest.setHeader(ORCHESTRATION_PROTOCOL_HEADER, String(ORCHESTRATION_PROTOCOL_VERSION)),
      ),
    ),
    HttpClient.filterStatusOk,
  );
  const projectId = ProjectId.make(randomUUID());
  yield* http.execute(
    HttpClientRequest.post(`${origin}/api/projects/mutate`).pipe(
      HttpClientRequest.bodyJsonUnsafe({
        type: "project.create",
        commandId: randomUUID(),
        projectId,
        title: "synthetic-archive",
        workspaceRoot,
      }),
    ),
  );
  const ticket = yield* http
    .execute(HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`))
    .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))));
  const protocol = yield* Layer.build(
    RpcClient.layerProtocolSocket().pipe(
      Layer.provide(
        Socket.layerWebSocket(
          `${origin!.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket.ticket)}`,
        ),
      ),
      Layer.provide(RpcSerialization.layerJson),
      Layer.provide(NodeWS.layerWebSocketConstructor),
    ),
  );
  const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
  let done = 0;
  yield* Effect.forEach(
    Array.from({ length: count }, (_, i) => i),
    (i) =>
      Effect.gen(function* () {
        const threadId = ThreadId.make(randomUUID());
        yield* client["orchestration.dispatchCommand"]({
          type: "thread.create",
          commandId: CommandId.make(randomUUID()),
          threadId,
          projectId,
          title: `Synthetic archived thread ${i + 1}`,
          modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
          runtimeMode: "full-access",
          interactionMode: "default",
          branch: null,
          worktreePath: null,
          createdBy: "user",
          creationSource: "web",
        } as never);
        yield* client["orchestration.dispatchCommand"]({
          type: "thread.archive",
          commandId: CommandId.make(randomUUID()),
          threadId,
        } as never);
        done++;
        if (done % 500 === 0) console.log(`archived ${done}`);
      }),
    { concurrency: 16, discard: true },
  );
  console.log(`done: ${done}`);
});

Effect.runPromise(program.pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))).then(
  () => process.exit(0),
  (error) => {
    console.error(error);
    process.exit(1);
  },
);
