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 lines = ["Updated src/**/*.ts files.", "Edit src/*/test/*.ts now.", "Matches **/*.test.ts files."];

test("Workflow agent summaries preserve literal glob asterisks", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("glob-summary");
  const definition = `export default T3.workflow("glob-summary", {version: 1, payload: Schema.Struct({})}, Effect.fn(function* () {
    ${lines.map((line, i) => `yield* T3.agent("reply-${i + 1}", {project: ${JSON.stringify(project)}, model: {instanceId: "opencode", model: "openai/gpt-6-luna"}, brief: ${JSON.stringify(`Reply with exactly this line verbatim, without backticks, explanation, or tools: ${line}`)}});`).join("\n")}
    return {done: true};
  }));`;
  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/glob-summary.ts"), definition);
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch: {
      workflowsEnabled: true,
      providerInstances: {opencode: {driver: "opencode", enabled: true}},
    }});
  }).pipe(Effect.scoped));
  const started = await runPromise(makeState(T3_HOME).cli(["workflow", "start", "glob-summary", "--key", "globs", "--json"]));
  const {run} = JSON.parse(started.stdout);
  await t3.open(`/workflows?run=${run.runId}`);
  const summaries = lines.map((_, i) => screen.getByRole("button", new RegExp(`^reply-${i + 1} `)).getByText(/^(Updated|Edit|Matches) /));
  for (const summary of summaries) await summary.waitFor({timeout: 180_000});
  await app.screenshot("workflow-glob-summaries");
  for (const [i, summary] of summaries.entries()) await expect(summary).toHaveText(lines[i]!);
});
