// Scratch driver for issue #43485. Not committed.
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NetService from "@t3tools/shared/Net";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { GlobalFlag } from "effect/cli";
import { withThreadTools } from "./src/cli/thread.ts";

const projectDir = process.argv[2]!;
const baseDir = process.argv[3]!;
const log = (label: string, value: unknown) =>
  Effect.sync(() => console.log(`== ${label}\n${JSON.stringify(value, null, 2)}`));

const program = withThreadTools(
  { baseDir: Option.some(baseDir), json: true, clientLabel: "repro-43485" },
  (tools) =>
    Effect.gen(function* () {
      const call = (name: string, args: Record<string, unknown>) =>
        tools.call(name, args, Schema.Unknown) as Effect.Effect<any, any, any>;
      const project = yield* call("t3_project_create", {
        title: "repro-43485",
        workspaceRoot: projectDir,
      });
      yield* log("project", { id: project.id });
      const launched = yield* call("t3_thread_launch", {
        projectId: project.id,
        title: "Plan child",
        modelSelection: { instanceId: "devReplay", model: "showcase" },
        runtimeMode: "full-access",
        interactionMode: "plan",
        message: "Propose a plan to add a CHANGELOG file.",
      });
      yield* log("launch", launched);
      yield* call("t3_thread_wait", { threadId: launched.threadId, timeoutMs: 40000 });
      const before = yield* call("t3_thread_read", { threadId: launched.threadId });
      yield* log("read after plan", {
        interactionMode: before.thread.interactionMode,
        runtimeMode: before.thread.runtimeMode,
        status: before.thread.status,
      });
      const sent = yield* call("t3_thread_send", {
        threadId: launched.threadId,
        message: "The plan is approved, please implement it.",
        mode: "auto",
      });
      yield* log("send", sent);
      yield* call("t3_thread_wait", { threadId: launched.threadId, timeoutMs: 40000 });
      const after = yield* call("t3_thread_read", { threadId: launched.threadId });
      yield* log("read after agent send", {
        interactionMode: after.thread.interactionMode,
        runtimeMode: after.thread.runtimeMode,
        status: after.thread.status,
        pendingRequestCount: after.thread.pendingRequestCount,
      });
      yield* log("thread keys", Object.keys(after.thread));
    }),
);

program.pipe(
  Effect.tapCause((c) => Effect.sync(() => console.error("CAUSE", JSON.stringify(c, null, 2), String(c)))),
  Effect.provideService(GlobalFlag.LogLevel, Option.none()),
  Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)),
  NodeRuntime.runMain,
);
