import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { NodeServices } from "@effect/platform-node";
import { withThreadTools } from "./src/cli/thread.ts";
import { GlobalFlag } from "effect/cli";
import * as Net from "@t3tools/shared/Net";
import * as Layer from "effect/Layer";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";

const baseDir = process.argv[2]!;
const repoRoot = process.argv[3]!;
const Any = Schema.Unknown;

const program = withThreadTools({ baseDir: Option.some(baseDir), json: true }, (tools) =>
  Effect.gen(function* () {
    const list: any = yield* tools.call("t3_project_list", { cursor: 0, limit: 100 }, Any);
    const project: any = list.projects.find((p: any) => p.workspaceRoot === repoRoot);
    console.log("project", project.id, JSON.stringify(project.repositoryIdentity));
    const thread: any = yield* tools.call("t3_thread_launch", { projectId: project.id, title: "repro", modelSelection: { instanceId: "devReplay", model: "showcase" } }, Any);
    console.log("thread", thread.threadId);
    const read: any = yield* tools.call("t3_project_read", { projectId: project.id }, Any);
    console.log("project identity", JSON.stringify(read.repositoryIdentity ?? read.project?.repositoryIdentity));
    for (const args of [
      { repository: "t3tools/t3code", number: 123 },
      { repository: "github.com/t3tools/t3code", number: 124 },
    ]) {
      const out = yield* tools
        .call("link_pull_request", { threadId: thread.threadId, ...args }, Any)
        .pipe(Effect.result);
      console.log("link_pull_request", JSON.stringify(args), "=>", JSON.stringify(out));
    }
  }),
);

program.pipe(Effect.provideService(GlobalFlag.LogLevel, Option.none()), Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, Net.layer)), Effect.runPromise).then(
  () => process.exit(0),
  (e) => {
    console.error("failed", e);
    process.exit(1);
  },
);
