import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const reply = "> ```sh\n> printf sample\n> ```\n\nBuild passed.";
test("Workflow step summary skips a quoted code fence", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("demo");
  const transcript = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await fs.readFile(transcript, "utf8");
  await fs.writeFile(transcript, [
    { 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: reply } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map(JSON.stringify).join("\n") + "\n");
  try {
    await fs.mkdir(path.join(T3_HOME, "workflows"), { recursive: true });
    await fs.writeFile(path.join(T3_HOME, "workflows/quoted-fence.ts"), `export default T3.workflow("quoted-fence", { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () { yield* T3.agent("reply", { project: ${JSON.stringify(project)}, model: { instanceId: "devReplay", model: "command-output" }, brief: ${JSON.stringify("Reply exactly with:\n" + reply)} }); }));`);
    await runPromise(Effect.gen(function* () {
      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", "quoted-fence", "--key", "proof", "--json"]));
    const { run } = JSON.parse(started.stdout);
    await t3.open(`/workflows?run=${run.runId}`);
    await screen.getByRole("region", "reply", { exact: true }).getByText("Build passed.", { exact: true }).waitFor({ timeout: 60000 });
    await screen.getByRole("region", "reply", { exact: true }).getByText("sample", { exact: true }).waitFor({ timeout: 60000 });
    await app.screenshot("quoted-fence-summary");
    await expect(screen.getByRole("button", /reply.*Build passed\./)).toBeVisible();
  } finally {
    await fs.writeFile(transcript, original);
  }
});
