/// <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 { test, WEB, rpcClient, runPromise } from "./t3.ts";

const LINK = "[example](t3-context://v1/file/demo)";
const INLINE = `Show the literal syntax: \`${LINK}\` Reply only with the exact characters inside the backticks of my message, and do not use any tools.`;
const CONTROL = `Control: ${LINK} Reply only with OK.`;

test("Inline context examples reach the provider literally; prose still projects", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo", { "provider-input.txt": "Waiting for provider input" });
  const wrapper = path.join(T3_HOME, "record-replay.mjs");
  const raw = path.join(project, "provider-prompts.jsonl");
  // Transparent transport recorder: all responses come from the repository's existing replay agent.
  await fs.writeFile(wrapper, `
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
import { appendFileSync, writeFileSync } from 'node:fs';
const child = spawn(process.execPath, [${JSON.stringify(path.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"))}], { stdio: ['pipe', 'inherit', 'inherit'] });
for await (const line of createInterface({ input: process.stdin })) {
  const frame = JSON.parse(line);
  if (frame.method === 'session/prompt') {
    const text = frame.params.prompt.filter(p => p.type === 'text').map(p => p.text).join('\\n');
    appendFileSync(${JSON.stringify(raw)}, JSON.stringify({ method: frame.method, text }) + '\\n');
  }
  child.stdin.write(line + '\\n');
}
child.stdin.end();
`);
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const original = await fs.readFile(settingsPath, "utf8");
  const settings = JSON.parse(original);
  settings.providerInstances.devReplay.config.commandArgs = [wrapper];
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  try {
    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 === "multi-turn"));
        }), Stream.runHead,
      );
    }).pipe(Effect.scoped));
    const thread = await t3.thread({ project, title: "Literal context syntax", messages: ["Start"] });
    await t3.open(thread);
    const composer = screen.getByRole("textbox");
    await composer.fill(INLINE);
    await composer.press("Enter");
    await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
    await composer.fill(CONTROL);
    await composer.press("Enter");
    await screen.getByText("first fixture turn complete", { exact: true }).nth(1).waitFor();
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
    const prompts = (await fs.readFile(raw, "utf8")).trim().split("\n").map(line => JSON.parse(line).text as string);
    const inline = prompts.find(text => text.includes("Show the literal syntax:"));
    const control = prompts.find(text => text.includes("Control:"));
    if (!inline || !control) throw new Error("Both composer messages must reach replay before comparing");
    // This is a view of observed transport data, not a generated provider response.
    const observed = `Observed session/prompt text sent to Replay (dev)\n\nINLINE EXAMPLE\n${inline}\n\nPROSE CONTROL\n${control}\n`;
    await fs.writeFile(path.join(project, "provider-input.txt"), observed);
    const evidence = await fs.mkdtemp("/tmp/factory-pr-46723-evidence-1/transport-");
    await fs.writeFile(path.join(evidence, "provider-input.txt"), observed);
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("provider-input.txt");
    await screen.getByRole("option", "provider-input.txt", { exact: false }).waitFor();
    await browser.keyboard.press("Enter");
    await screen.getByRole("dialog", "File picker").waitFor({ state: "hidden" });
    await screen.getByRole("button", "Copy contents", { exact: true }).waitFor();
    await app.screenshot("provider-input");
    await expect(inline).toBe(INLINE);
    await expect(control).toContain('[File: example; ref=demo]');
    await expect(control).toContain('<context kind="file" id="demo" unavailable="true"/>');
  } finally {
    await fs.writeFile(settingsPath, original);
  }
});
