import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import { ProjectId } from "@t3tools/contracts";
import { rpcClient } from "./scenarios/t3.ts";

const [home, origin, projectId, ...numbers] = process.argv.slice(2);
const rounds = [0, 20, 70, 660];

const program = Effect.scoped(
  Effect.gen(function* () {
    const client = yield* rpcClient(home!, origin!);
    const start = Date.now();
    for (const at of rounds) {
      const wait = start + at * 1000 - Date.now();
      if (wait > 0) yield* Effect.sleep(`${wait} millis`);
      const roundStart = new Date().toISOString();
      const results = yield* Effect.forEach(
        numbers.flatMap((n) => {
          const ref = {
            projectId: ProjectId.make(projectId!),
            repository: "pingdotgg/t3code",
            number: Number(n),
          };
          return [
            client["pullRequests.detail"](ref).pipe(Effect.map((d) => `detail ${n} ${d.state}`)),
            client["pullRequests.detail"](ref).pipe(Effect.map((d) => `detail ${n} ${d.state}`)),
            client["pullRequests.detail"](ref).pipe(Effect.map((d) => `detail ${n} ${d.state}`)),
            client["pullRequests.checks"](ref).pipe(
              Effect.map((c) => `checks ${n} ${c === null ? "null" : c.state}`),
            ),
          ];
        }),
        (e) => Effect.result(e),
        { concurrency: "unbounded" },
      );
      console.log(
        JSON.stringify({
          round: at,
          roundStart,
          roundEnd: new Date().toISOString(),
          results: results.map((r) => (r._tag === "Success" ? r.success : String(r.failure))),
        }),
      );
    }
  }),
);

Effect.runPromise(program.pipe(Effect.provide(NodeServices.layer))).catch((e) => {
  console.error(e);
  process.exit(1);
});
