// @effect-diagnostics nodeBuiltinImport:off globalTimers:off - scratch repro driver for #44307, not committed.
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeNet from "node:net";
import * as NodePath from "node:path";
import * as NodeWS from "@effect/platform-node/NodeWS";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
  CommandId,
  MessageId,
  ORCHESTRATION_PROTOCOL_HEADER,
  ORCHESTRATION_PROTOCOL_VERSION,
  ProjectId,
  ProviderInstanceId,
  ThreadId,
  WsRpcGroup,
  type OrchestrationV2ThreadProjection,
} 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";

const REPO_ROOT = NodePath.resolve(import.meta.dirname, "..");
const OUT = process.argv[2]!;
const uuid = Effect.flatMap(SecureRandom.SecureRandom, (r) => r.uuidV4());
const log = (...a: unknown[]) => console.log(new Date().toISOString().slice(11, 23), ...a);

const freePort = () =>
  Effect.callback<number>((resume) => {
    const s = NodeNet.createServer();
    s.listen(0, () => {
      const a = s.address();
      s.close(() => resume(Effect.succeed(typeof a === "object" && a ? a.port : 0)));
    });
  });
const portOpen = (port: number) =>
  Effect.callback<boolean>((resume) => {
    const s = NodeNet.connect(port, "127.0.0.1");
    s.once("connect", () => (s.destroy(), resume(Effect.succeed(true))));
    s.once("error", () => resume(Effect.succeed(false)));
  });

const main = Effect.gen(function* () {
  const baseDir = NodePath.join(OUT, "base");
  const workspace = NodePath.join(OUT, "workspace");
  NodeFS.mkdirSync(workspace, { recursive: true });
  for (let i = 0; i < 150; i++)
    NodeFS.writeFileSync(NodePath.join(workspace, `module${String(i).padStart(3, "0")}.txt`), `module ${i}: value ${(i * 7919) % 1000}\n`);
  NodeChildProcess.execSync(
    "git init -q && git add . && git -c user.email=a@b -c user.name=a commit -qm init",
    { cwd: workspace },
  );
  const port = yield* freePort();
  const serverLog = NodeFS.openSync(NodePath.join(OUT, "server.log"), "w");
  const child = yield* Effect.acquireRelease(
    Effect.sync(() =>
      NodeChildProcess.spawn(
        "node",
        [
          "apps/server/src/bin.ts",
          "serve",
          "--host",
          "127.0.0.1",
          "--port",
          String(port),
          "--base-dir",
          baseDir,
          "--no-browser",
          "--log-level",
          "info",
          workspace,
        ],
        {
          cwd: REPO_ROOT,
          stdio: ["ignore", serverLog, serverLog],
          env: { ...process.env, T3CODE_DEV_SEED: "0" },
        },
      ),
    ),
    (c) => Effect.sync(() => c.kill("SIGTERM")),
  );
  log("server pid", child.pid, "port", port);
  for (let i = 0; i < 240 && !(yield* portOpen(port)); i++) yield* Effect.sleep("500 millis");
  const origin = `http://127.0.0.1:${port}`;
  let issued = "";
  for (let i = 0; i < 20 && issued === ""; i++) {
    try {
      issued = NodeChildProcess.execFileSync(
        "node",
        ["apps/server/src/bin.ts", "auth", "session", "issue", "--base-dir", baseDir, "--token-only"],
        { cwd: REPO_ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
      );
    } catch {
      yield* Effect.sleep("1 second");
    }
  }
  const token = issued.split("\n").filter((l) => l.trim()).at(-1)!.trim();
  const http = (yield* HttpClient.HttpClient).pipe(
    HttpClient.mapRequest((r) =>
      r.pipe(
        HttpClientRequest.bearerToken(token),
        HttpClientRequest.setHeader(ORCHESTRATION_PROTOCOL_HEADER, String(ORCHESTRATION_PROTOCOL_VERSION)),
      ),
    ),
    HttpClient.filterStatusOk,
  );
  for (let i = 0; i < 120; i++) {
    const ok = yield* http.get(`${origin}/api/orchestration/shell`).pipe(
      Effect.as(true),
      Effect.catch(() => Effect.succeed(false)),
    );
    if (ok) break;
    yield* Effect.sleep("1 second");
  }
  const projectId = ProjectId.make(yield* uuid);
  yield* http.execute(
    HttpClientRequest.post(`${origin}/api/projects/mutate`).pipe(
      HttpClientRequest.bodyJsonUnsafe({
        type: "project.create",
        commandId: yield* uuid,
        projectId,
        title: "repro",
        workspaceRoot: workspace,
      }),
    ),
  );
  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));
  const command = Effect.map(uuid, CommandId.make);
  const projection = (threadId: ThreadId) => client["orchestration.getThreadProjection"]({ threadId });
  const modelSelection = {
    instanceId: ProviderInstanceId.make("claudeAgent"),
    model: "claude-haiku-5-5",
  };

  const threadId = ThreadId.make(yield* uuid);
  yield* client["orchestration.launchThread"]({
    commandId: yield* command,
    threadId,
    projectId,
    title: "Plan with background agent",
    modelSelection,
    runtimeMode: "full-access",
    interactionMode: "plan",
    workspaceStrategy: { type: "root" },
    initialMessage: {
      text:
        "Use the Agent tool with run_in_background set to true to start exactly one Explore subagent (read-only investigation). " +
        "Its task: read each of the 150 files module000.txt through module149.txt in this folder with the Read tool, one file per Read call, in order, never batching, then report the sum of all values. " +
        "Do not wait for it and do not check on it. As soon as it is launched, reply with the single word 'launched' and end your turn.",
      attachments: [],
    },
  });
  log("launched plan thread", threadId);

  const summarize = (p: OrchestrationV2ThreadProjection) => ({
    mode: `${p.thread.runtimeMode}/${p.thread.interactionMode}`,
    runs: p.runs.map((r) => {
      const { status } = r as { status: string };
      const extra = r as unknown as Record<string, unknown>;
      return { status, error: extra.error ?? extra.failure ?? extra.lastError ?? undefined };
    }),
    subagents: p.subagents.map((s) => (s as unknown as { status: string }).status),
    pendingRequests: p.runtimeRequests.filter((r) => (r as { status: string }).status === "pending").length,
  });

  // Approve any approval the plan turn's subagent asks for, until run 1 ends with a subagent still running.
  for (let i = 0; i < 600; i++) {
    const p = yield* projection(threadId);
    for (const req of p.runtimeRequests) {
      const r = req as unknown as { id: string; status: string; kind?: string };
      if (r.status === "pending") {
        log("approving runtime request", r.id, r.kind);
        yield* client["orchestration.dispatchCommand"]({
          type: "runtime-request.respond",
          commandId: yield* command,
          threadId,
          requestId: r.id as never,
          decision: "accept",
        } as never);
      }
    }
    const run1 = p.runs[0] as { status: string } | undefined;
    if (run1 && ["completed", "failed", "interrupted", "cancelled"].includes(run1.status)) {
      log("run 1 ended", JSON.stringify(summarize(p)));
      break;
    }
    yield* Effect.sleep("1 second");
  }
  NodeFS.writeFileSync(NodePath.join(OUT, "after-run1.json"), JSON.stringify(yield* projection(threadId), null, 1));
  yield* Effect.sleep("3 seconds");

  // What mobile sends: the Plan-to-Build switch, then the follow-up.
  for (let attempt = 1; attempt <= 3; attempt++) {
    yield* client["orchestration.dispatchCommand"]({
      type: "thread.interaction-mode.set",
      commandId: yield* command,
      threadId,
      interactionMode: "default",
    });
    yield* client["orchestration.dispatchCommand"]({
      type: "message.dispatch",
      commandId: yield* command,
      threadId,
      messageId: MessageId.make(yield* uuid),
      text: `Follow-up ${attempt}: reply with the word 'ack'.`,
      attachments: [],
      dispatchMode: { type: "queue_after_active" },
      createdBy: "user",
      creationSource: "mobile",
    } as never);
    log(`follow-up ${attempt} dispatched`);
    for (let i = 0; i < 120; i++) {
      const p = yield* projection(threadId);
      const last = p.runs.at(-1) as { status: string } | undefined;
      if (p.runs.length >= 1 + attempt && last && ["completed", "failed", "interrupted", "cancelled"].includes(last.status)) {
        log(`after follow-up ${attempt}`, JSON.stringify(summarize(p)));
        break;
      }
      yield* Effect.sleep("1 second");
    }
  }
  const final = yield* projection(threadId);
  NodeFS.writeFileSync(NodePath.join(OUT, "final.json"), JSON.stringify(final, null, 1));
  log("final", JSON.stringify(summarize(final)));
}).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer));

main.pipe(Effect.provide([NodeServices.layer, NodeCrypto.layer]), NodeRuntime.runMain);
