import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const TITLE = "Quarterly infrastructure review covering deploy latency, error budgets, cache hit rates, and the new rollout plan for Q🚀";
const CONTROL = "Quarterly infrastructure review covering deploy latency, error budgets, cache hit rates, and the new rollout plan for🚀";

// Keep the Replay agent's ACP transport, but publish the synthetic reports through its real MCP server.
const publish = `
        const { spawn } = await import("node:child_process");
        const server = scenarioMcpServers.find(s => s.command);
        if (!server) throw new Error("No stdio MCP server was supplied to Replay");
        const child = spawn(server.command, server.args ?? [], { env: { ...process.env, ...Object.fromEntries((server.env ?? []).map(e => [e.name,e.value])) }, stdio: ["pipe", "pipe", "pipe"] });
        const pending = new Map();
        let sequence = 0;
        NodeReadline.createInterface({input:child.stdout}).on("line", line => {
          const msg = JSON.parse(line);
          if (pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
        });
        const call = async (method, params) => {
          const id = ++sequence;
          const response = new Promise(resolve => pending.set(id, resolve));
          child.stdin.write(JSON.stringify({jsonrpc:"2.0",id,method,params})+"\\n");
          const msg = await response;
          if (msg.error) throw new Error(JSON.stringify(msg.error));
          return msg.result;
        };
        try {
          await call("initialize", {protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"report-scenario",version:"1"}});
          child.stdin.write(JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})+"\\n");
          for (const [index,title] of ${JSON.stringify([CONTROL,TITLE])}.entries()) {
            const input = {title, height:220, html:'<!doctype html><html><head><style>body{font:18px system-ui;padding:28px}h1{font-size:28px}</style></head><body><h1>'+ (index === 0 ? 'Control report (emoji fits)' : 'Hello report')+'</h1><p>It works.</p></body></html>'};
            const result = await call("tools/call", {name:"html_render",arguments:input});
            if(result.isError) throw new Error(JSON.stringify(result));
            send({method:"session/update",params:{sessionId,update:{sessionUpdate:"tool_call",toolCallId:"report-"+index,kind:"other",title:"t3-code.html_render",status:"completed",rawInput:input,rawOutput:result}}});
          }
        } finally {child.kill();}
        return {stopReason:"end_turn"};
`;

test("HTML reports load when the filename limit crosses an emoji", WEB, async ({t3,app,browser,screen}) => {
  const agentPath = path.join(APP_DIR,"apps/server/scripts/dev-replay-agent.ts");
  const original = await fs.readFile(agentPath,"utf8");
  const patched = original.replace('function runAgent(): void {','let scenarioMcpServers: any[] = [];\nfunction runAgent(): void {')
    .replace('const cwd = typeof params.cwd', 'scenarioMcpServers = params.mcpServers as any[];\n        const cwd = typeof params.cwd')
    .replace('const turns = loadTurns(session.model);',publish+'\n        const turns = loadTurns(session.model);');
  await fs.writeFile(agentPath,patched);
  try {
    const project = await t3.project("report-demo");
    const thread = await t3.thread({project,title:"HTML report emoji boundary",messages:["Show the control report and the filename-boundary report."]});
    await t3.open(thread);
    const control = browser.frameLocator(`iframe[title="${CONTROL}"]`);
    await control.locator("body").waitFor();
    await expect(control.locator("body")).toContainText("Control report (emoji fits)");
    const report = browser.frameLocator(`iframe[title="${TITLE}"]`);
    try {
      await expect(browser.locator(`iframe[title="${TITLE}"]`)).toHaveCount(1);
      await expect(report.locator("body")).toContainText("Hello report");
      await expect(report.locator("body")).toContainText("It works.");
    } finally { await app.screenshot("inline-reports"); }
    await screen.getByRole("button","Open full screen",{exact:true}).last().tap();
    try {
      await expect(browser.frameLocator(`[role="dialog"] iframe`).locator("body")).toContainText("Hello report");
    } finally {await app.screenshot("full-screen-report");}
  } finally {await fs.writeFile(agentPath,original);}
});
