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

test("Explicit preview_open reports the attached Browser panel", WEB, async ({t3,app,screen,browser}) => {
  // Extend only the free replay driver's response: call the real scoped MCP endpoint.
  const agent = `${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`;
  const original = await readFile(agent, "utf8");
  const injected = original
    .replace('loadSession: true,', 'loadSession: true, mcpCapabilities: { http: true, sse: true },')
    .replace('const sessions = new Map<', 'const mcpBySession = new Map<string, any>();\n  const sessions = new Map<')
    .replace('sessions.set(sessionId, { cwd,', 'mcpBySession.set(sessionId, params.mcpServers);\n        sessions.set(sessionId, { cwd,')
    .replace('const turns = loadTurns(session.model);', `
        if (JSON.stringify(params.prompt).includes("Call preview_open with url https://example.org")) {
          const servers = mcpBySession.get(sessionId) ?? [];
          const stdio = servers.find((s:any)=>s.env);
          const env = Object.fromEntries((stdio?.env ?? []).map((e:any)=>[e.name,e.value]));
          const server = servers.find((s: any) => s.type === "http") ?? (env.T3_ACP_MCP_ENDPOINT ? {url:env.T3_ACP_MCP_ENDPOINT,headers:[{name:"Authorization",value:env.T3_ACP_MCP_AUTHORIZATION}]} : null);
          if (!server) throw new Error("No scoped HTTP MCP server");
          let rpcId = 0;
          let mcpSession = "";
          const rpc = async (method: string, body: any, notify = false) => {
            const response = await fetch(server.url, {method:"POST", headers: {
              "content-type":"application/json", accept:"application/json, text/event-stream",
              ...Object.fromEntries(server.headers.map((h:any) => [h.name,h.value])),
              ...(mcpSession ? {"mcp-session-id":mcpSession} : {})
            }, body:JSON.stringify({jsonrpc:"2.0", ...(notify ? {} : {id:++rpcId}), method,params:body})});
            mcpSession = response.headers.get("mcp-session-id") || mcpSession;
            const text = await response.text();
            if (!response.ok) throw new Error("MCP HTTP " + response.status + " " + text);
            if (notify) return;
            const result = text.startsWith("{") ? JSON.parse(text) : text.split("\\n").filter(l=>l.startsWith("data:")).map(l=>JSON.parse(l.slice(5))).find(m=>m.id===rpcId);
            if (result.error) throw new Error(JSON.stringify(result.error));
            return result.result;
          };
          await rpc("initialize", {protocolVersion:"2025-06-18", capabilities:{}, clientInfo:{name:"scenario",version:"1"}});
          await rpc("notifications/initialized", {}, true);
          const opened = await rpc("tools/call", {name:"preview_open", arguments:{url:"https://example.org",open:true,reuseExistingTab:false}});
          const value = (r:any) => r.structuredContent ?? JSON.parse(r.content.find((c:any)=>c.type==="text").text);
          const open = value(opened);
          if (opened.isError) throw new Error(JSON.stringify(open));
          await new Promise(resolve=>setTimeout(resolve,1200));
          const status = value(await rpc("tools/call", {name:"preview_status",arguments:{tabId:open.tabId}}));
          send({method:"session/update",params:{sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:
            "preview_open returned visible: " + open.visible + "\\n\\nSubsequent preview_status visible: " + status.visible + "\\n\\nURL: " + status.url
          }}}});
          return {stopReason:"end_turn"};
        }
        const turns = loadTurns(session.model);`);
  await writeFile(agent,injected);
  try {
    const project = await t3.project("Browser visibility");
    await t3.thread({project,title:"Preview visibility",messages:["Ready"]});
    await t3.open();
    await browser.locator("[data-thread-item]").first().tap();
    await screen.getByRole("textbox").fill("Call preview_open with url https://example.org, open:true, reuseExistingTab:false, then preview_status for that tab.");
    await screen.getByRole("textbox").press("Enter");
    await screen.getByText("Subsequent preview_status visible:",{exact:false}).first().waitFor({state:"visible",timeout:60000});
    await app.screenshot("preview-open-result-and-browser");
    await expect(screen.getByText("preview_open returned visible: true",{exact:false})).toBeVisible();
  } finally { await writeFile(agent,original); }
});
