import { CommandId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { makeState, rpcClient, runPromise } from "./t3.ts";

const [home, origin] = process.argv.slice(2);
if (!home || !origin) throw new Error("Usage: handoff-seed.ts <isolated-home> <origin>");
const {state, cli} = makeState(home);
const project = await state.project("Handoff demo");
const thread = await state.thread({project, title: "Provider handoff", messages: ["first"]});
await runPromise(Effect.gen(function* () {
  const client = yield* rpcClient(home, origin);
  const settings = yield* client["server.getSettings"]({});
  yield* client["server.updateSettings"]({patch: {}, providerInstanceMutation: {operation: "create", instanceId: ProviderInstanceId.make("replayAfter"), instance: {...settings.providerInstances.devReplay!, displayName: "Replay After", enabled: true}}});
  yield* client.subscribeServerConfig({}).pipe(Stream.filter(event => (event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : []).some(provider => provider.instanceId === "replayAfter")), Stream.runHead);
  yield* client["orchestration.dispatchCommand"]({type: "thread.model-selection.set", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(thread.threadId), modelSelection: {instanceId: ProviderInstanceId.make("replayAfter"), model: "multi-turn"}});
  yield* cli(["thread", "send", thread.threadId, "Continue after the handoff", "--wait", "--json"]);
}).pipe(Effect.scoped));
console.log(JSON.stringify(thread));
