import * as fs from "node:fs/promises";
import * as path 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 identifiers = "Set MY_API_KEY in src/__tests__/my_module.test.ts now.";
const inline = "Run `__init__` now.";
const transcript = (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") + "\n";

test("Workflow feed preserves underscores in identifiers, paths and inline code", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1160, height: 800 });
  const project = await t3.project("underscore-demo");
  const thread = await t3.thread({ project, title: "Workflow proof", messages: ["Start"] });
  const recordings = [
    [path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson"), identifiers],
    [path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson"), inline],
  ];
  const originals = await Promise.all(recordings.map(async ([file]) => fs.readFile(file, "utf8")));
  const definition = path.join(T3_HOME, "workflows/underscore-repro.ts");
  try {
    for (const [file, reply] of recordings) await fs.writeFile(file, transcript(reply));
    await fs.mkdir(path.dirname(definition), { recursive: true });
    await fs.writeFile(definition, `export default T3.workflow("underscore-repro", { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () {
      yield* T3.agent("identifiers", { project: ${JSON.stringify(project)}, brief: ${JSON.stringify("Reply exactly: " + identifiers)}, model: { instanceId: "devReplay", model: "command-output" } });
      yield* T3.agent("inline-code", { project: ${JSON.stringify(project)}, brief: ${JSON.stringify("Reply exactly: " + inline)}, model: { instanceId: "devReplay", model: "showcase" } });
    }));`);
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
    }).pipe(Effect.scoped, Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 30 })));
    const started = await runPromise(makeState(T3_HOME).cli(["workflow", "start", "underscore-repro", "--key", "proof", "--json"]));
    const { run } = JSON.parse(started.stdout);
    await t3.open(thread);
    await t3.open(`/workflows?run=${run.runId}`);
    await screen.getByText("Finished", { exact: true }).first().waitFor({ timeout: 90_000 });
    await app.screenshot("workflow-feed-underscores");
    await expect(screen.getByRole("button", "identifiers " + identifiers, { exact: false })).toBeVisible();
    await expect(screen.getByRole("button", "inline-code Run __init__ now.", { exact: false })).toBeVisible();
  } finally {
    for (let i = 0; i < recordings.length; i++) await fs.writeFile(recordings[i][0], originals[i]);
  }
});
