/// <reference lib="dom" />
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 Stream from "effect/Stream";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const literal = 'Before :codex-followup{prompt="Look at [foo]"} after';
const labeled = 'Before :codex-followup[Ask]{prompt="go"} after';

// The free replay agent supplies the reported assistant text; copying and pasting use the real UI.
function transcript(text: string) {
  return [
    { 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("Copy keeps a literal unlabeled follow-up and a labeled follow-up's visible label", WEB, async ({ t3, app, screen, browser }) => {
  const files = ["showcase_transcript.ndjson", "command_output_transcript.ndjson"].map(name => path.join(APP_DIR, "apps/server/scripts/dev-replay", name));
  const originals = await Promise.all(files.map(file => fs.readFile(file, "utf8")));
  try {
    await fs.writeFile(files[0]!, transcript(literal));
    await fs.writeFile(files[1]!, transcript(labeled));
    const project = await t3.project("Copy follow-up");
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl!);
      yield* client.subscribeServerConfig({}).pipe(
        Stream.filter(event => {
          const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
          return providers.some(provider => provider.instanceId === "devReplay" && provider.models?.some(model => model.slug === "command-output"));
        }), Stream.runHead);
    }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
    const unlabeled = await t3.thread({ project, title: "Unlabeled follow-up", model: "showcase", messages: [`Reply with exactly this single line as plain text: ${literal}`] });
    const control = await t3.thread({ project, title: "Labeled follow-up control", model: "command-output", messages: [`Reply with exactly this single line as plain text: ${labeled}`] });
    await t3.open(unlabeled);
    await screen.getByText(literal, { exact: true }).waitFor();
    await screen.getByRole("button", "Copy message", { exact: true }).tap();
    const composer = screen.getByRole("textbox");
    await composer.tap();
    await browser.keyboard.press("ControlOrMeta+v");
    const pasted = await browser.evaluate(() => document.querySelector('[contenteditable="true"][role="textbox"]')?.textContent ?? "");
    await app.screenshot("unlabeled-copy-pasted");
    await t3.open(control);
    await screen.getByText("Before Ask after", { exact: true }).waitFor();
    await screen.getByRole("button", "Copy message", { exact: true }).tap();
    await screen.getByRole("textbox").tap();
    await browser.keyboard.press("ControlOrMeta+v");
    await app.screenshot("labeled-control-pasted");
    await expect(screen.getByRole("textbox")).toHaveText("Before Ask after");
    expect(pasted).toBe(literal);
  } finally {
    await Promise.all(files.map((file, i) => fs.writeFile(file, originals[i]!)));
  }
});
