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

const cases = [
  { name: "Backtick reply", model: "showcase", file: "apps/server/scripts/dev-replay/showcase_transcript.ndjson", reply: '```json\n{"ok": true}\n```\nAll good. Next.' },
  { name: "Tilde reply", model: "command-output", file: "apps/server/scripts/dev-replay/command_output_transcript.ndjson", reply: '~~~json\n{"ok": true}\n~~~\nAll good. Next.' },
  { name: "Code only", model: "bench-heavy", file: "apps/server/scripts/dev-replay/bench_heavy_transcript.ndjson", reply: '```json\n{"ok": true}\n```' },
  { name: "Unclosed fence", model: "bench-stream", file: "apps/server/scripts/dev-replay/bench_stream_transcript.ndjson", reply: '```json\n{"ok": true}' },
];

test("Workflow feed skips fenced code to the first prose sentence", WEB, async ({ t3, app, browser }) => {
  const originals = cases.map(c => readFileSync(join(APP_DIR, c.file), "utf8"));
  try {
    for (const c of cases) {
      writeFileSync(join(APP_DIR, c.file), [
        { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
        { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: c.reply } } } } },
        { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
      ].map(x => JSON.stringify(x)).join("\n"));
    }
    const project = await t3.project("Fenced reply proof");
    const definition = join(T3_HOME, "workflows/fenced.ts");
    mkdirSync(dirname(definition), { recursive: true });
    writeFileSync(definition, `export default T3.workflow("fenced", { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () {
      yield* T3.title("Fenced reply summaries");
      ${cases.map(c => `yield* T3.agent(${JSON.stringify(c.name)}, { project: ${JSON.stringify(project)}, model: { instanceId: "devReplay", model: ${JSON.stringify(c.model)} }, brief: ${JSON.stringify("Reply exactly with:\n" + c.reply)} });`).join("\n")}
    }));`);
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
    }).pipe(Effect.scoped));
    const cli = makeState(T3_HOME).cli;
    const started = JSON.parse((await runPromise(cli(["workflow", "start", "fenced", "--key", "proof", "--json"]))).stdout);
    const runId = started.run.runId;
    await runPromise(Effect.gen(function* () {
      const detail = JSON.parse((yield* cli(["workflow", "show", runId, "--json"])).stdout);
      if (detail.run.endedAt === null) return yield* Effect.fail("running");
      if (detail.run.status !== "completed") throw new Error(JSON.stringify(detail));
    }).pipe(Effect.retry({ schedule: Schedule.spaced("1 second"), times: 90 })));
    await t3.open(`/workflows?run=${runId}`);
    await runPromise(Effect.tryPromise(() => browser.evaluate(`(() => { const n = document.querySelector('nav[aria-label="Steps so far"]'); if (!n?.textContent.includes("Unclosed fence")) throw Error("waiting for feed"); return true; })()`)).pipe(Effect.retry({ schedule: Schedule.spaced("300 millis"), times: 100 })));
    await app.screenshot("fenced-reply-feed");
    const rows = await browser.evaluate<string[]>(`[...document.querySelectorAll('nav[aria-label="Steps so far"] li')].map(x => x.textContent)`);
    expect(rows.filter(x => x.includes("All good.")).length).toBe(2);
    expect(rows.some(x => x.includes('{"ok": true}') || x.includes("~~~"))).toBe(false);
  } finally {
    cases.forEach((c, i) => writeFileSync(join(APP_DIR, c.file), originals[i]));
  }
});
