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 DOCX = "UEsDBBQAAAAIAIajeV10JJxTuwAAAD4BAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbJWQuQ7CMAyGX6XKiqgRAwNquwArMPACVuq2EbkUuxxvT8o1sDHa//FZrk73SFzcnPVcq0EkrgFYD+SQyxDJZ6ULyaHkMfUQUZ+xJ1guFivQwQt5mcvUoZpqSx2OVordLa/ZBF+rRJZVsXkZJ1atMEZrNErW4eLbH8r8TShz8unhwUSeZYOCpjpcKCXTUnHEJHt0uQ6uIbXQBj26jCgn41+80HVG0zc/tcUUNDEb3ztbfhWHxn/ugOfbmgdQSwMEFAAAAAgAhqN5XWF7L0OJAAAA8gAAAAsAAABfcmVscy8ucmVsc43POw4CIRAG4KsQDrCzWlgYoLLZ1ngBAsMjLo8MGPX2UlisxsJy5p98f0accdU9ltxCrI090pqb5KH3egRoJmDSbSoV80hcoaT7GMlD1eaqPcJ+ng9AW4MrsTXZYiWnxe44uzwr/mMX56LBUzG3hLn/qPi6GLImj13yeyEL9r2eBstBCfh4Ub0AUEsDBBQAAAAIAIajeV3BHwOh/AAAABYCAAARAAAAd29yZC9kb2N1bWVudC54bWyVkt1KxDAQhV+lBG91dmWrELaFZUHw1jdI07ENmz8niXXf3qRrLYKi3kya03O+YYbsJ947mQzaWL0ZbQOfGjbG6DlAkCMaEW6cR5v/PTsyIuYrDTA56j05iSEoOxgNt5vNHRihLPvAGPkXjhF0Sv5aOuNFVJ3SKp5n1oKZtruGJbLlY9XqRatZZSR/HKwj0WlsWLZVRW73E+9cfy6nL4VKmWfkwQuZrZ4wIL0iaw/GpTx/n5BXe8i2ttScyOyDjkhWRDw6G/OWZvE4OiWxesKXpDKltL20vHRpr+7rLxz4zPwU3/0j/iC07oQ8/ZJYbfDtHDBvBpY9wfoS2ndQSwECFAMUAAAACACGo3lddCScU7sAAAA+AQAAEwAAAAAAAAAAAAAAgAEAAAAAW0NvbnRlbnRfVHlwZXNdLnhtbFBLAQIUAxQAAAAIAIajeV1hey9DiQAAAPIAAAALAAAAAAAAAAAAAACAAewAAABfcmVscy8ucmVsc1BLAQIUAxQAAAAIAIajeV3BHwOh/AAAABYCAAARAAAAAAAAAAAAAACAAZ4BAAB3b3JkL2RvY3VtZW50LnhtbFBLBQYAAAAAAwADALkAAADJAgAAAAA=";
const AGENT = "\nimport { createInterface } from 'node:readline';\nimport { execFileSync } from 'node:child_process';\nconst sessionId='docx-proof';\nconst send=m=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...m})+'\\n');\nfor await (const line of createInterface({input:process.stdin})) {\n const {id,method,params}=JSON.parse(line); if(id===undefined) continue;\n let result={};\n if(method==='initialize') result={protocolVersion:1,agentInfo:{name:'Document reader',version:'1.0'},agentCapabilities:{promptCapabilities:{embeddedContext:true}},authMethods:[]};\n if(method==='session/new') result={sessionId};\n if(method==='session/prompt') {\n  const text=(params.prompt??[]).filter(x=>x.type==='text').map(x=>x.text).join('\\n');\n  const match=text.match(/text extracted to: ([^)]+)/);\n  const reply=match ? '```\\n'+execFileSync('cat',[match[1]],{encoding:'utf8'})+'\\n```' : 'Ready for invoice.docx.';\n  send({method:'session/update',params:{sessionId,update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:reply}}}});\n  result={stopReason:'end_turn'};\n }\n send({id,result});\n}\n";
test("A DOCX supplies one alternate representation to the agent", WEB, async ({t3,app,browser,screen}) => {
 const project=await t3.project("Invoice");
 const script=path.join(project,"document-reader.mjs");
 await fs.writeFile(script,AGENT);
 const settingsPath=path.join(T3_HOME,"userdata/settings.json");
 const settings=JSON.parse(await fs.readFile(settingsPath,"utf8"));
 settings.providerInstances["document-reader"]={driver:"acpRegistry",displayName:"Document reader",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[script]}};
 await fs.writeFile(settingsPath,JSON.stringify(settings));
 const {cli}=makeState(T3_HOME);
 let threadId;
 for(let attempt=0;attempt<8 && !threadId;attempt++) {
  const started=await runPromise(cli(["thread","start",project,"Prepare to read an invoice.","--title","Invoice extraction","--provider","document-reader","--model","default","--wait","--json"],[0,1]));
  if(started.stdout.includes('threadId')) threadId=JSON.parse(started.stdout).threadId;
 }
 if(!threadId) throw new Error("Could not start document reader");
 await t3.open({threadId});
 await screen.getByText("Ready for invoice.docx.",{exact:true}).waitFor();
 await screen.getByRole("textbox").fill("Run `cat` on the extracted-text file of the attached DOCX and paste its full content verbatim in a code block. Do nothing else.");
 await browser.evaluate((base64:string)=>{
  const input=document.querySelector<HTMLInputElement>('form[data-chat-composer-form] input[type="file"]');
  if(!input) throw new Error("No attachment input");
  const files=new DataTransfer();
  files.items.add(new File([Uint8Array.from(atob(base64),c=>c.charCodeAt(0))],"invoice.docx",{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}));
  input.files=files.files; input.dispatchEvent(new Event("change",{bubbles:true}));
 },DOCX);
 await screen.getByText("invoice.docx",{exact:true}).first().waitFor();
 await screen.getByRole("button","Submit message",{exact:true}).tap();
 await screen.getByText("Amount due:",{exact:false}).waitFor({timeout:60000});
 await app.screenshot("invoice-extracted-text");
 await expect(screen.getByText("Amount due:",{exact:false})).toHaveText("Amount due: $75");
});
