/// <reference lib="dom" />
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Completed CR-only shell fences offer Run in terminal", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson");
  const original = await readFile(fixture, "utf8");
  const project = await t3.project("Shell fence examples");
  const cases = [
    { label: "LF closed", text: "```sh\necho hi\n```", run: true },
    { label: "CRLF closed", text: "```sh\r\necho hi\r\n```", run: true },
    { label: "CR closed", text: "```sh\recho hi\r```", run: true },
    { label: "CR unclosed", text: "```sh\recho hi", run: false },
    { label: "LF unclosed", text: "```sh\necho hi", run: false },
  ];
  const agent = await readFile(join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), "utf8");
  const fixtureFiles = {};
  for (const [index, sample] of cases.entries()) {
    const entries = original.trim().split("\n").map((line) => JSON.parse(line));
    for (const entry of entries) {
      if (entry.frame?.params?.update?.sessionUpdate === "agent_message_chunk") entry.frame.params.update.content.text = sample.text;
    }
    fixtureFiles[`case-${index}.ndjson`] = entries.map((entry) => JSON.stringify(entry)).join("\n") + "\n";
  }
  const start = agent.indexOf("export const SCENARIOS = [");
  const end = agent.indexOf("] as const;", start) + "] as const;".length;
  const models = cases.map((sample, index) => ({ id: `case-${index}`, name: sample.label, file: `./case-${index}.ndjson` }));
  const replayProject = await t3.project("Replay fixtures", {
    ...fixtureFiles,
    ...Object.fromEntries(cases.map((sample, index) => [`replay-${index}.ts`, agent.slice(0, start) + "export const SCENARIOS = " + JSON.stringify([{ id: "default", name: sample.label, file: `./case-${index}.ndjson` }]) + ";" + agent.slice(end)])),
  });
  const settingsPath = join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  for (const [index] of cases.entries()) settings.providerInstances[`fenceReplay${index}`] = { driver: "acpRegistry", displayName: "Replay shell examples", enabled: true,
    config: { source: "local", commandPath: process.execPath, commandArgs: [join(replayProject, `replay-${index}.ts`)] } };
  await writeFile(settingsPath, JSON.stringify(settings));
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client.subscribeServerConfig({}).pipe(Stream.filter((event) =>
      (event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : []).some((provider) => provider.instanceId === "fenceReplay4")), Stream.runHead);
  }).pipe(Effect.scoped));
  const seeded = [];
  const { cli } = makeState(T3_HOME);
  for (const [index, sample] of cases.entries()) {
    const result = await runPromise(cli(["thread", "start", project, "Show the shell example.", "--title", sample.label,
      "--provider", `fenceReplay${index}`, "--model", "default", "--wait", "--json"]));
    seeded.push({ ...sample, thread: JSON.parse(result.stdout) });
  }
  const observed = [];
  for (const sample of seeded) {
    await t3.open(sample.thread);
    await screen.getByRole("button", "Copy code", { exact: true }).waitFor();
    await screen.getByText("echo hi", { exact: true }).waitFor();
    await browser.locator('text="Syncing messages"').waitFor({ state: "hidden" });
    await app.screenshot(sample.label.toLowerCase().replaceAll(" ", "-"));
    const count = await browser.evaluate(() => document.querySelectorAll('.chat-markdown-codeblock[data-language="sh"] button[aria-label="Run in terminal"]').length);
    observed.push({ label: sample.label, run: count === 1 });
  }
  await expect(observed).toEqual(cases.map(({ label, run }) => ({ label, run })));
});
