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

const html = `<!doctype html><html><head><meta charset="utf-8"></head><body style="font:16px system-ui;padding:24px;background:#f8fafc;color:#172033"><h1 style="font-size:24px">WebAssembly MCP App</h1><p>Compile and instantiate a minimal WebAssembly module.</p><pre id="result" style="white-space:pre-wrap;overflow-wrap:anywhere;padding:16px;border:1px solid #94a3b8;border-radius:8px">Starting WebAssembly…</pre><script>
(async () => { const result = document.getElementById('result'); try { await WebAssembly.instantiate(new Uint8Array([0,0x61,0x73,0x6d,1,0,0,0])); result.textContent = 'WASM OK: module compiled and instantiated'; result.style.color = '#166534'; } catch(error) { result.textContent = 'WASM FAILED: ' + error; result.style.color = '#b91c1c'; } })();
parent.postMessage({jsonrpc:'2.0',id:'init',method:'ui/initialize',params:{protocolVersion:'2026-01-26',appInfo:{name:'WASM demo',version:'1.0.0'},appCapabilities:{}}}, '*');
addEventListener('message', event => { if(event.data?.id === 'init') parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/initialized'},'*'); });
</script></body></html>`;
const server = `import {createInterface} from 'node:readline';
const html = ${JSON.stringify(html)};
for await (const line of createInterface({input:process.stdin})) { let m; try {m=JSON.parse(line)} catch {continue} if(m.id===undefined) continue; let result;
switch(m.method) {
case 'initialize': result={protocolVersion:'2025-03-26',capabilities:{tools:{},resources:{}},serverInfo:{name:'wasm-demo',version:'1.0.0'}}; break;
case 'tools/list': result={tools:[{name:'show_wasm_app',description:'Show the WebAssembly demo app',inputSchema:{type:'object',properties:{}},_meta:{ui:{resourceUri:'ui://wasm-demo/app.html'}}}]}; break;
case 'tools/call': result={content:[{type:'text',text:'WebAssembly demo opened.'}]}; break;
case 'resources/list': result={resources:[{uri:'ui://wasm-demo/app.html',name:'WebAssembly demo',mimeType:'text/html;profile=mcp-app'}]}; break;
case 'resources/read': result={contents:[{uri:'ui://wasm-demo/app.html',mimeType:'text/html;profile=mcp-app',text:html}]}; break;
default: result={};
} process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n'); }
`;

test("MCP Apps compile WebAssembly inside the chat frame", WEB, async ({t3, app, browser}) => {
  const project = await t3.project("wasm-demo", {
    "wasm-server.mjs": server,
    ".mcp.json": JSON.stringify({mcpServers:{"wasm-demo":{command:process.execPath,args:["wasm-server.mjs"]}}}),
    ".claude/settings.json": JSON.stringify({enableAllProjectMcpServers:true}),
  });
  await t3.thread({project,title:"Setup",messages:["Start"]});
  const settingsPath = path.join(T3_HOME,"userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath,"utf8"));
  settings.providerInstances.claudeAgent = {driver:"claudeAgent",enabled:true,config:{}};
  await fs.writeFile(settingsPath,JSON.stringify(settings));
  const {cli} = makeState(T3_HOME);
  let threadId: string | undefined;
  for(let attempt=0;attempt<8 && threadId===undefined;attempt++) {
    const started = await runPromise(cli(["thread","start",project,"Call mcp__wasm-demo__show_wasm_app once. Do not read files or call any other tools. Then say: Here is the WebAssembly demo.","--title","WebAssembly MCP App","--provider","claudeAgent","--model","claude-haiku-5-5","--wait","--json"],[0,1,2]));
    if(started.stdout.includes('threadId')) threadId=JSON.parse(started.stdout).threadId;
  }
  if(!threadId) throw new Error("Could not start Claude MCP App thread");
  await t3.open({threadId});
  const frame = browser.frameLocator('iframe[title="wasm-demo app"]');
  await frame.locator("#result").waitFor({timeout:120000});
  await expect.poll(()=>frame.locator("#result").textContent()).toMatch(/WASM (OK|FAILED):/);
  await app.screenshot("wasm-app-result");
  await expect(frame.locator("#result")).toContainText("WASM OK: module compiled and instantiated");
});
