import { readFileSync } from "node:fs";
import { CommandId, ThreadId, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { makeState, rpcClient, runPromise } from "./t3.ts";

export async function emptyReplayThread(home: string) {
  const { origin } = JSON.parse(readFileSync(`${home}/userdata/server-runtime.json`, "utf8"));
  const issued = await runPromise(makeState(home).cli(["auth", "session", "issue", "--token-only"]));
  const response = await fetch(`${origin}/api/orchestration/shell`, { headers: {
    authorization: `Bearer ${issued.stdout.trim()}`,
    "x-t3-orchestration-protocol": String(ORCHESTRATION_PROTOCOL_VERSION),
  }});
  const snapshot = await response.json();
  const threadId = ThreadId.make(crypto.randomUUID());
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(home, origin);
    yield* client["orchestration.dispatchCommand"]({
      type: "thread.create", commandId: CommandId.make(crypto.randomUUID()),
      threadId, projectId: snapshot.projects[0].id, title: "Stopped turn tour",
      createdBy: "user", creationSource: "web", modelSelection: { instanceId: "devReplay", model: "showcase" },
      runtimeMode: "full-access", interactionMode: "default", branch: "main", worktreePath: null,
    });
  }).pipe(Effect.scoped));
  return { threadId };
}
