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

const cases = [
  { name: "issue-number", model: "showcase", file: "scripts/dev-replay/showcase_transcript.ndjson", reply: "#4512 is merged.\nTests pass.", summary: "#4512 is merged." },
  { name: "quoted-heading", model: "command-output", file: "scripts/dev-replay/command_output_transcript.ndjson", reply: "> ## Summary\n\nAll good.", summary: "All good." },
  { name: "seven-hashes", model: "bench-heavy", file: "scripts/dev-replay/bench_heavy_transcript.ndjson", reply: "####### Seven hashes.\nok.", summary: "####### Seven hashes." },
];
const recording = (text: string) => [
  { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
  { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } },
  { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
].map(x => JSON.stringify(x)).join("\n");

test("Workflow summaries preserve hash prose and skip quoted headings", WEB, async ({ t3, app, screen }) => {
  const restore = await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const originals = [];
    for (const item of cases) {
      const file = path.join(APP_DIR, "apps/server", item.file);
      originals.push({ file, text: yield* fs.readFileString(file) });
      yield* fs.writeFileString(file, recording(item.reply));
    }
    return Effect.forEach(originals, item => fs.writeFileString(item.file, item.text), { discard: true });
  }));
  try {
    const project = await t3.project("summary-demo");
    const definition = `export default T3.workflow("summary-check", { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () {\n${cases.map(item => `yield* T3.agent(${JSON.stringify(item.name)}, { project: ${JSON.stringify(project)}, brief: ${JSON.stringify("Reply exactly:\n" + item.reply)}, model: { instanceId: "devReplay", model: ${JSON.stringify(item.model)} } });`).join("\n")}\n}));`;
    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/summary-check.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", "summary-check", "--key", "proof", "--json"]));
    const { run } = JSON.parse(started.stdout);
    await t3.open(`/workflows?run=${run.runId}`);
    await screen.getByRole("button", "seven-hashes", { exact: false }).waitFor({ timeout: 90000 });
    // A completed third step has its reply's prose in both versions, though the chosen line differs.
    await screen.getByRole("button", /seven-hashes.*(ok\.|Seven hashes\.)/).waitFor({ timeout: 90000 });
    await app.screenshot("workflow-step-summaries");
    for (const item of cases) {
      await expect(screen.getByRole("button", item.name, { exact: false })).toContainText(item.summary);
    }
  } finally { await runPromise(restore); }
});
