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

const SCRATCH = "/tmp/factory-pr-43817-evidence-4";
const INPUT = "\uFEFF```md\n[example](t3-context://v1/file/demo)\n```\nQuote the fenced line and report any XML-like tags.";

test("BOM fenced examples stay literal and prose links become context", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("examples");
  const settingsPath=path.join(T3_HOME,"userdata/settings.json");
  const settings=JSON.parse(await fs.readFile(settingsPath,"utf8"));
  const output=path.join(SCRATCH,`projection-${Date.now()}.ndjson`);
  settings.providerInstances.observer={driver:"acpRegistry",displayName:"Prompt observer",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[path.join(SCRATCH,"observer.mjs"),output]}};
  await fs.writeFile(settingsPath,JSON.stringify(settings));

  const {cli}=makeState(T3_HOME);
  let thread;
  for(let attempt=0;attempt<8;attempt++){
    const result=await runPromise(cli(["thread","start",project,INPUT,"--title","Context examples","--provider","observer","--model","default","--wait","--json"],[0,1]));
    if(result.stdout.includes("threadId")){thread=JSON.parse(result.stdout);break;}
  }
  if(!thread) throw new Error("Observer did not register");
  await t3.open(thread);
  await screen.getByText("Received user prompt",{exact:false}).first().waitFor();
  await screen.getByText("Quote the fenced line and report any XML-like tags.",{exact:false}).last().waitFor();
  await app.screenshot("provider-projection-bom-preserved");
  const received=JSON.parse((await fs.readFile(output,"utf8")).trim().split("\n").at(-1)!);
  const composer = screen.getByRole("textbox");
  await composer.tap();
  await browser.evaluate((threadId: string) => {
    const env = decodeURIComponent(window.location.pathname.split("/")[1]!);
    const link = `<t3-thread://v2/${env}/${threadId}>`;
    const clipboardData = new DataTransfer();
    clipboardData.setData("text/plain", `\uFEFF~~~\n${link}\n~~~\n${link}`);
    document.activeElement!.dispatchEvent(new ClipboardEvent("paste", {clipboardData,bubbles:true,cancelable:true}));
  },thread.threadId);
  await app.screenshot("bom-fence-paste");
  const structure=await browser.evaluate(()=>{
    const editor=document.querySelector('[data-testid="composer-editor"]')!;
    const code=editor.querySelector("pre")!;
    return (editor.textContent ?? "").indexOf("t3-thread://") < (editor.textContent ?? "").lastIndexOf("Context examples");
  });
  // The actual server-to-provider payload must preserve the example with no generated context.
  expect(received.prompt).toContain("[example](t3-context://v1/file/demo)");
  expect(received.prompt).not.toContain('<t3_context version="1">');
  expect(structure).toBe(true);
});
