import { expect } from "e2e";
import fs from "node:fs/promises";
import { test, WEB, makeState, rpcClient, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";
import * as Effect from "effect/Effect";

test("Quoted image paths remain prose while image references inline", WEB, async ({ t3, app, browser }) => {
  const project = await t3.project("image-prose", { "imgs/chart.png": new Uint8Array(await fs.readFile("/tmp/factory-pr-46117-a1796049929-evidence-1/chart.png")) });
  const thread = await t3.thread({ project, title: "Quoted image paths", messages: ["start"], model: "default" });
  await fs.writeFile("/tmp/factory-pr-46117-a1796049929-evidence-1/hold", "hold");
  await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Keep this run active for HTML proof", "--json"]));
  await t3.open(thread);
  const session = JSON.parse(await fs.readFile("/tmp/factory-pr-46117-a1796049929-evidence-1/session.json", "utf8"));
  const server = session.mcpServers.find((s: any) => s.name === "t3-code");
  if (!server) throw new Error(`No T3 MCP server: ${JSON.stringify(session)}`);
  const headers: Record<string,string> = {accept: "application/json, text/event-stream", "content-type": "application/json"};
  const env = Object.fromEntries(server.env.map((e: any)=>[e.name,e.value]));
  headers.authorization = env.T3_ACP_MCP_AUTHORIZATION;
  let id = 0;
  async function send(method: string, params?: unknown) {
    const response = await fetch(env.T3_ACP_MCP_ENDPOINT, { method: "POST", headers, body: JSON.stringify({jsonrpc:"2.0", ...(method.startsWith("notifications/") ? {} : {id: ++id}), method, params}) });
    const sid = response.headers.get("mcp-session-id"); if(sid) headers["mcp-session-id"] = sid;
    const body = await response.text();
    if (!response.ok) throw new Error(`MCP ${response.status}: ${body}`);
    if (!body) return {};
    const data = body.startsWith("event:") ? body.split("\n").filter(l=>l.startsWith("data:")).map(l=>l.slice(5)).join("") : body;
    return JSON.parse(data);
  }
  await send("initialize", {protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"proof",version:"1"}});
  await send("notifications/initialized");
  const call = async (name: string, args: unknown) => await send("tools/call",{name,arguments:args});
  const missingHtml = `<p>Delete "/tmp/factory-pr-46117-a1796049929-evidence-1/old.png" before rerunning.</p>`;
  const chartHtml = `<p>Output written to "/tmp/factory-pr-46117-a1796049929-evidence-1/chart.png".</p><img src="/tmp/factory-pr-46117-a1796049929-evidence-1/chart.png">`;
  const missing = await call("html_render", {title:"Repro missing",height:200,html:missingHtml});
  const chart = await call("html_render", {title:"Repro chart",height:200,html:chartHtml});
  const chartPreview = await call("html_preview", {html:chartHtml,width:1000,appearance:"light"});
  const missingPreview = await call("html_preview", {html:missingHtml,width:1000,appearance:"light"});
  await fs.writeFile("/tmp/factory-pr-46117-a1796049929-evidence-1/results.json",JSON.stringify({missing,chart,chartPreview,missingPreview}));
  await fs.writeFile("/tmp/factory-pr-46117-a1796049929-evidence-1/hold", "release");
  const resultOf = (response: any) => response.result?.structuredContent ?? JSON.parse(response.result?.content?.find((c: any)=>c.type==="text")?.text ?? "{}");
  const chartResult = resultOf(chart);
  const previewResult = resultOf(chartPreview);
  const missingPreviewResult = resultOf(missingPreview);
  const resource = { _tag: "attachment" as const, attachmentId: chartResult.htmlRender.attachmentId, fileName:"chart.html",mimeType:"text/html",disposition:"inline" as const };
  const url = await runPromise(Effect.scoped(Effect.gen(function*(){ const rpc = yield* rpcClient(T3_HOME, app.baseUrl ?? ""); return yield* rpc["assets.createUrl"]({resource}); })));
  await app.open(url.relativeUrl);
  const page = await browser.evaluate<string>(`document.documentElement.outerHTML`);
  await app.screenshot("published-chart");
  // The PNG below comes directly from the real html_preview response.
  const png = chartPreview.result.content.find((c: any)=>c.type==="image");
  await fs.writeFile("/tmp/factory-pr-46117-a1796049929-evidence-1/preview.png", Buffer.from(png.data,"base64"));
  await app.open("data:text/html," + encodeURIComponent(`<body style="margin:0;background:white"><img src="data:image/png;base64,${png.data}"></body>`));
  await app.screenshot("preview-chart");
  expect({missingRenderFailed: missing.result?.isError ?? !!missing.error, proseIsLiteral: page.includes('Output written to \"/tmp/factory-pr-46117-a1796049929-evidence-1/chart.png\"'), actualImageInlined: page.includes('src="data:image/png;base64,'), missingImages: missingPreviewResult.missingImages ?? []}).toEqual({missingRenderFailed:false,proseIsLiteral:true,actualImageInlined:true,missingImages:[]});
});
