/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const LINK = "[example](t3-context://v1/file/demo)";
const INTRO = "Do not run any tools. Reply with only the exact code example below, character for character, inside a code block:";
const FENCE = "```md\n" + LINK + "\n```";
const MESSAGE = INTRO + "\n\n" + FENCE;
// Transparent tap around the real Replay agent: show the exact text delivered to the provider.
// Recorded replies still come from Replay; this diagnostic contains no projection logic.
const WRAPPER = `
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
const child = spawn(process.execPath, [${JSON.stringify(path.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"))}], {stdio:['pipe','pipe','inherit']});
child.stdout.pipe(process.stdout);
for await (const line of createInterface({input:process.stdin})) {
  const message = JSON.parse(line);
  if (message.method === 'session/prompt') {
    const text = (message.params.prompt ?? []).filter(p => p.type === 'text').map(p => p.text).find(t => t.includes(${JSON.stringify(INTRO)}));
    if (text) process.stdout.write(JSON.stringify({jsonrpc:'2.0',method:'session/update',params:{sessionId:message.params.sessionId,update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:'Provider received:\\n\\n~~~~text\\n' + text + '\\n~~~~\\n\\n'}}}}) + '\\n');
  }
  child.stdin.write(line + '\\n');
}
child.stdin.end();
`;

test("A fenced context link reaches the provider literally while an outside reference projects", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("context-example");
  const settingsFile = path.join(T3_HOME, "userdata/settings.json");
  const original = await fs.readFile(settingsFile, "utf8");
  const settings = JSON.parse(original);
  const wrapper = path.join(project, "replay-prompt-tap.mjs");
  await fs.writeFile(wrapper, WRAPPER);
  settings.providerInstances.devReplay.config.commandArgs = [wrapper];
  await fs.writeFile(settingsFile, JSON.stringify(settings));
  try {
    const thread = await t3.thread({project, title:"Fenced context example", messages:["Start"], model:"multi-turn"});
    await t3.open(thread);
    const composer = screen.getByRole("textbox");
    const paste = async (text: string) => {
      await browser.evaluate((value) => navigator.clipboard.writeText(value), text);
      await composer.tap();
      await browser.keyboard.press("ControlOrMeta+V");
    };
    await paste(MESSAGE);
    await app.screenshot("fenced-composer");
    await screen.getByRole("button", "Submit message", { exact: true }).tap();
    await screen.getByText("second fixture turn complete").waitFor();
    await app.screenshot("fenced-provider-input");
    const firstInput = await browser.evaluate(() => [...document.querySelectorAll("pre code")].map(n => n.textContent).find(t => t?.includes("Do not run any tools.")) ?? "");
    await paste(MESSAGE + "\n\nOutside: " + LINK);
    await screen.getByRole("button", "Submit message", { exact: true }).tap();
    await screen.getByText("Outside: [File: example; ref=demo]", { exact: false }).waitFor();
    await app.screenshot("outside-control-provider-input");
    const inputs = await browser.evaluate(() => [...document.querySelectorAll("pre code")].map(n => n.textContent).filter(t => t?.includes("Do not run any tools.")));
    await expect(firstInput.trim()).toBe(MESSAGE);
    await expect(inputs.at(-1)?.trim()).toBe(MESSAGE + '\n\nOutside: [File: example; ref=demo]\n\n<t3_context version="1">\n<context kind="file" id="demo" unavailable="true"/>\n</t3_context>');
  } finally { await fs.writeFile(settingsFile, original); }
});
