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

export async function seed(t3: T3State, home: string, origin: string) {
  const project = await t3.project("demo");
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const client = yield* rpcClient(home, origin);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter((event) => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some(p => p.instanceId === "devReplay" && p.models?.some(m => m.slug === "multi-turn"));
      }), Stream.runHead,
    );
  })).pipe(Effect.timeout("60 seconds")));
  const one = await t3.thread({ project, title: "One linked issue", messages: ["Start"] });
  const many = await t3.thread({ project, title: "Many linked items", messages: ["Start"] });
  const issued = await runPromise(makeState(home).cli(["auth", "session", "issue", "--token-only"]));
  const { projects } = await (await fetch(`${origin}/api/projects`, { headers: { authorization: `Bearer ${issued.stdout.trim()}` } })).json();
  const projectId = ProjectId.make(projects.find((p: { title: string }) => p.title === "demo").id);
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const client = yield* rpcClient(home, origin);
    for (const [thread, numbers] of [[one, [84]], [many, Array.from({length:14}, (_,i)=>101+i)]] as const) {
      for (const number of numbers) yield* client["orchestration.dispatchCommand"]({
        type: "thread.issue.link", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(thread.threadId),
        tracker: "github", host: "github.com", scope: "demo/example", key: String(number), projectId,
        url: `https://github.com/demo/example/issues/${number}`, displayKey: `#${number}`, title: `Issue number ${number}`, source: "manual",
      });
    }
    for (let number = 201; number <= 213; number++) yield* client["orchestration.dispatchCommand"]({
      type: "thread.pull-request.link", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(many.threadId),
      host: "github.com", repository: "demo/example", number, url: `https://github.com/demo/example/pull/${number}`, source: "manual",
    });
  })));
  return { one, many };
}
