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

const definition = `export default T3.workflow("bigbrief", {version:1, payload: Schema.Struct({threadId: Schema.String}), returns: Schema.String}, ({threadId}) => Effect.map(T3.agent("report", { thread: {threadId}, brief: "x".repeat(150_000) }), d => String(d.value)));`;

test("Workflow receives the length refusal before an oversized message is stored", WEB, async ({t3, app, screen}) => {
  const project = await t3.project("Length limit demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter((event) => (event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : []).some((provider) => provider.instanceId === "devReplay" && provider.models.some((model) => model.slug === "multi-turn"))),
      Stream.runHead,
      Effect.timeout("60 seconds"),
    );
  }).pipe(Effect.scoped));
  const thread = await t3.thread({project, title: "Workflow length limit", messages: ["hello"], model: "multi-turn"});
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(`${T3_HOME}/workflows`, {recursive:true});
    yield* fs.writeFileString(`${T3_HOME}/workflows/bigbrief.ts`, definition);
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch:{workflowsEnabled:true}});
  }).pipe(Effect.scoped));
  const started = await runPromise(makeState(T3_HOME).cli(["workflow", "start", "bigbrief", "--key", "r1", "--input", JSON.stringify({threadId:thread.threadId}), "--json"]));
  const {run} = JSON.parse(started.stdout);
  await t3.open(`/workflows?run=${run.runId}`);
  const why = screen.getByRole("region", "Why it paused");
  await why.waitFor({timeout:30_000});
  await app.screenshot("workflow-error");
  await t3.open(thread);
  await screen.getByText("hello", {exact:true}).waitFor({timeout:30_000});
  await screen.getByText("Syncing messages...", {exact:true}).waitFor({state:"hidden"});
  await app.screenshot("thread-after-workflow");
  await t3.open(`/workflows?run=${run.runId}`);
  await why.waitFor({timeout:30_000});
  await expect(why).toContainText("120,000");
  await expect(why).toContainText("150,000");
  const shown = await runPromise(makeState(T3_HOME).cli(["thread", "show", thread.threadId, "--json"]));
  await expect(shown.stdout.includes("x".repeat(150_000))).toBe(false);
});
