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 AGENT = String.raw`
import { createInterface } from 'node:readline';
const send = x => process.stdout.write(JSON.stringify({jsonrpc:'2.0',...x})+'\n');
const update = x => send({method:'session/update',params:{sessionId:'comment-replay',update:x}});
let server;
for await (const line of createInterface({input:process.stdin})) {
 const {id,method,params} = JSON.parse(line);
 if(id===undefined) continue;
 if(method==='initialize') send({id,result:{protocolVersion:1,agentInfo:{name:'Comment replay',version:'1'},agentCapabilities:{},authMethods:[]}});
 else if(method==='session/new') { server=params.mcpServers[0]; send({id,result:{sessionId:'comment-replay'}}); }
 else if(method==='session/prompt') {
  const env=Object.fromEntries(server.env.map(x=>[x.name,x.value]));
  let session;
  const call=async message=>{
   const r=await fetch(env.T3_ACP_MCP_ENDPOINT,{method:'POST',headers:{accept:'application/json, text/event-stream','content-type':'application/json',authorization:env.T3_ACP_MCP_AUTHORIZATION,...(session?{'mcp-session-id':session}:{})},body:JSON.stringify({jsonrpc:'2.0',...message})});
   session=r.headers.get('mcp-session-id')||session;
   const text=await r.text();
   if(!text) return {};
   return JSON.parse(text.startsWith('event:')||text.startsWith('data:')?text.split('\n').filter(x=>x.startsWith('data:')).map(x=>x.slice(5).trim()).join(''):text);
  };
  await call({id:1,method:'initialize',params:{protocolVersion:'2025-06-18',capabilities:{},clientInfo:{name:'comment-replay',version:'1'}}});
  await call({method:'notifications/initialized'});
  update({sessionUpdate:'tool_call',toolCallId:'render-comment',title:'html_render',kind:'other',status:'in_progress',rawInput:{html:'<!-- <img src="/tmp/comment-missing.png"> --><p>ok</p>',title:'Comment repro',height:80}});
  const result=await call({id:2,method:'tools/call',params:{name:'html_render',arguments:{html:'<!-- <img src="/tmp/comment-missing.png"> --><p>ok</p>',title:'Comment repro',height:80}}});
  update({sessionUpdate:'tool_call_update',toolCallId:'render-comment',status:result.result?.isError?'failed':'completed',rawOutput:result.result||result,content:[{type:'content',content:{type:'text',text:JSON.stringify(result.result||result)}}]});
  update({sessionUpdate:'agent_message_chunk',content:{type:'text',text:'Comment render call complete.\n'+(result.result?.isError ? JSON.stringify(result.result) : 'Render published.')}});
  send({id,result:{stopReason:'end_turn'}});
 } else send({id,result:{}});
}
`;

test('Commented-out missing images do not block HTML rendering', WEB, async ({t3,app,screen,browser})=>{
 await fs.access('/tmp/comment-missing.png').then(()=>{throw new Error('Reproduction path must not exist');},()=>{});
 const project=await t3.project('demo');
 const settingsPath=path.join(T3_HOME,'userdata/settings.json');
 const original=await fs.readFile(settingsPath,'utf8');
 const settings=JSON.parse(original);
 const script=path.join(project,'comment-replay.mjs');
 await fs.writeFile(script,AGENT);
 settings.providerInstances['comment-replay']={driver:'acpRegistry',displayName:'Comment replay',enabled:true,config:{source:'local',commandPath:process.execPath,commandArgs:[script]}};
 await fs.writeFile(settingsPath,JSON.stringify(settings));
 try {
  const {cli}=makeState(T3_HOME);
  let threadId;
  for(let i=0;i<8 && !threadId;i++) {
   const r=await runPromise(cli(['thread','start',project,'Render the HTML comment reproduction exactly once.','--title','Comment repro','--provider','comment-replay','--model','default','--wait','--json'],[0,1]));
   if(r.stdout.includes('threadId')) threadId=JSON.parse(r.stdout).threadId;
  }
  if(!threadId) throw new Error('Replay thread did not start');
  await t3.open({threadId});
  await screen.getByText('Comment render call complete.',{exact:false}).waitFor();
  const worked = screen.getByRole('button', /^Worked for/);
  if(await worked.isVisible()) await worked.tap();
  try {
   expect(await browser.evaluate(() => document.body.textContent.includes('Render published.')), 'The real html_render call publishes the commented HTML').toBe(true);
   await expect(browser.frameLocator('iframe[title="Comment repro"]').locator('body')).toContainText('ok');
   const preserved = await browser.evaluate(async () => {
    const frame = document.querySelector('iframe[title="Comment repro"]');
    return (await (await fetch(frame.src)).text()).includes('<!-- <img src="/tmp/comment-missing.png"> -->');
   });
   expect(preserved, 'The published HTML preserves the comment').toBe(true);
  } finally { await app.screenshot('comment-render'); }
 } finally {await fs.writeFile(settingsPath,original);}
});
