import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const definition = `export default T3.workflow("poolorder", {
 version: 1, payload: Schema.Struct({ kind: Schema.String }), resumeAfter: []
}, (payload) => Effect.gen(function* () {
 yield* T3.title(payload.kind);
 const wait = (name) => T3.wait(name, { returns: Schema.Null });
 if (payload.kind.startsWith("wide")) {
  yield* T3.within("shared", { limit: 2 }, wait("release"));
  return;
 }
 const body = Effect.gen(function* () {
  yield* wait("go");
  yield* T3.step("work", { returns: Schema.Void, retry: { times: 0 } }, Effect.gen(function* () {
   const fail = yield* T3.store.entry("poolorder/fail", Schema.Boolean).get;
   if (Option.getOrElse(fail, () => false)) yield* Effect.fail("deliberate pause");
  }));
  yield* wait("done");
 });
 if (payload.kind === "A") {
  yield* T3.within("first", { limit: 1 }, Effect.gen(function* () {
   yield* wait("take-shared");
   yield* T3.within("shared", { limit: 2 }, body);
  }));
 } else yield* T3.within("shared", { limit: 2 }, body);
}));`;

test("Resumed multi-pool runs display allocator consideration order", WEB, async ({ t3, app, screen }) => {
 const cli = async (args: string[]) => (await runPromise(makeState(T3_HOME).cli(["workflow", ...args]))).stdout;
 const show = async (id: string) => JSON.parse(await cli(["show", id, "--json"]));
 const until = async (id: string, predicate: (s: any) => boolean) => {
  for (let n = 0; n < 40; n++) { const s = await show(id); if (predicate(s)) return s; }
  throw new Error("workflow milestone not reached");
 };
 const waiting = (name: string) => (s: any) => s.run.status === "waiting" && s.steps.some((x: any) => x.name === name && x.status === "running");
 const start = async (kind: string) => JSON.parse(await cli(["start", "poolorder", "--key", kind, "--input", JSON.stringify({kind}), "--json"])).run.runId;
 const signal = (id: string, wait: string) => cli(["signal", "null", "--run", id, "--wait", wait]);
 await runPromise(Effect.gen(function* () {
  const fs = yield* FileSystem.FileSystem;
  const path = yield* Path.Path;
  yield* fs.makeDirectory(path.join(T3_HOME, "workflows"), {recursive:true});
  yield* fs.writeFileString(path.join(T3_HOME, "workflows/poolorder.ts"), definition);
 }));
 await t3.project("Queue order demonstration");
 await runPromise(Effect.gen(function* () {
  const client = yield* rpcClient(T3_HOME, app.baseUrl!);
  yield* client["server.updateSettings"]({patch:{workflowsEnabled:true}});
 }).pipe(Effect.scoped));
 await cli(["store", "set", "poolorder/fail", "true"]);
 const a = await start("A"); await until(a, waiting("take-shared"));
 const b = await start("B"); await until(b, waiting("go"));
 await signal(a, "take-shared"); await until(a, waiting("go"));
 await signal(a, "go"); await signal(b, "go");
 await until(a, s => s.run.status === "paused"); await until(b, s => s.run.status === "paused");
 const wide1 = await start("wide-1"); await until(wide1, waiting("release"));
 const wide2 = await start("wide-2"); await until(wide2, waiting("release"));
 await cli(["store", "set", "poolorder/fail", "false"]);
 await cli(["resume", a]); await cli(["resume", b]);
 await until(a, s => s.run.status === "waiting" && s.run.detail?.startsWith("queue ")); await until(b, s => s.run.status === "waiting" && s.run.detail?.startsWith("queue "));
 await t3.open(`/workflows?run=${a}`);
 const aStep = screen.getByRole("button", /@pool:shared/);
 await aStep.waitFor();
 await app.screenshot("A-shared-queue-position");
 const aText = await aStep.textContent();
 await t3.open(`/workflows?run=${b}`);
 const bStep = screen.getByRole("button", /@pool:shared/);
 await bStep.waitFor();
 await app.screenshot("B-shared-queue-position");
 const bText = await bStep.textContent();
 await signal(wide1, "release");
 await until(a, waiting("done"));
 await t3.open(`/workflows?run=${a}`);
 await screen.getByRole("button", /^done/).waitFor();
 await app.screenshot("A-admitted-after-one-place-frees");
 await expect(aText).toContain("queued, next in line");
 await expect(bText).toContain("queued, 1 ahead");
});
