/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
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 = (body: string) => new Uint8Array(execFileSync("python3", ["-c", `
import io,sys,zipfile
b=io.BytesIO()
with zipfile.ZipFile(b,'w',zipfile.ZIP_DEFLATED) as z:
 z.writestr('[Content_Types].xml','<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>')
 z.writestr('_rels/.rels','<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>')
 z.writestr('word/document.xml',sys.argv[1])
sys.stdout.buffer.write(b.getvalue())
`, `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><w:body>${body}</w:body></w:document>`]));
const tracked = docx('<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Real heading</w:t></w:r></w:p><w:p><w:pPr><w:pPrChange w:id="1" w:author="Example" w:date="2026-01-01T00:00:00Z"><w:pPr><w:pStyle w:val="Heading2"/></w:pPr></w:pPrChange></w:pPr><w:r><w:t>Body text</w:t></w:r></w:p>');
const box = docx('<w:p><w:r><w:t xml:space="preserve">Intro. </w:t></w:r><w:r><w:drawing><wp:anchor><wps:wsp><wps:txbx><w:txbxContent><w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Box title</w:t></w:r></w:p></w:txbxContent></wps:txbx></wps:wsp></wp:anchor></w:drawing></w:r></w:p>');

// This agent reads only the real sidecars named in T3's attachment prompt.
const reader = String.raw`
import { createInterface } from 'node:readline';
import { readFileSync, writeFileSync } from 'node:fs';
const sessionId='docx-reader';
const send=m=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...m})+'\n');
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,agentCapabilities:{promptCapabilities:{embeddedContext:true}},authMethods:[]}});
 else if(method==='session/new') send({id,result:{sessionId}});
 else if(method==='session/prompt') {
  const text=(params.prompt??[]).filter(x=>x.type==='text').map(x=>x.text).join('\n');
  const matches=[...text.matchAll(/text extracted to: ([^)\n]+)/g)];
  let reply='Ready for the two Word documents.';
  if(matches.length) {
   const results=matches.map(m=>readFileSync(m[1].replace(/^"|"$/g,''),'utf8'));
   writeFileSync(new URL('./extracted.json',import.meta.url),JSON.stringify(results));
   const names=['tracked-format-change.docx','text-box.docx'];
   reply='Verbatim extracted text (read from the server-created .txt files):\n\n'+results.map((s,i)=>names[i]+'\n\n'+ '\x60\x60\x60text\n'+s+'\n\x60\x60\x60').join('\n\n')+'\n\nExtraction read complete.';
  }
  send({method:'session/update',params:{sessionId,update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:reply}}}});
  send({id,result:{stopReason:'end_turn'}});
 } else send({id,result:{}});
}
`;

test('Word body paragraphs stay plain while real headings retain their markers', WEB, async ({t3, app, browser, screen}) => {
 const project=await t3.project('Word extraction', {'tracked-format-change.docx':tracked,'text-box.docx':box,'reader.mjs':reader});
 const settingsPath=path.join(T3_HOME,'userdata/settings.json');
 const original=await fs.readFile(settingsPath,'utf8');
 const settings=JSON.parse(original);
 settings.providerInstances['docx-reader']={driver:'acpRegistry',displayName:'Document reader',enabled:true,config:{source:'local',commandPath:process.execPath,commandArgs:[path.join(project,'reader.mjs')]}};
 await fs.writeFile(settingsPath,JSON.stringify(settings));
 try {
  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,'Prepare to read two Word attachments.','--title','Word paragraph extraction','--provider','docx-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 the two Word documents.',{exact:true}).waitFor();
  await browser.setViewport({width:1280,height:1000});
  await screen.getByRole('button','Toggle thread details panel').tap();
  const composer=screen.getByRole('textbox');
  await composer.fill('Read each attached document’s “text extracted to” .txt file and quote it verbatim in a code block.');
  await browser.evaluate((files: {name:string;bytes:number[]}[])=>{
   const input=document.querySelector('input[type="file"]') as HTMLInputElement;
   const transfer=new DataTransfer();
   for(const f of files) transfer.items.add(new File([new Uint8Array(f.bytes)],f.name,{type:'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}));
   input.files=transfer.files;
   input.dispatchEvent(new Event('change',{bubbles:true}));
  },[{name:'tracked-format-change.docx',bytes:[...tracked]},{name:'text-box.docx',bytes:[...box]}]);
  await screen.getByRole('button','File attachment, tracked-format-change.docx',{exact:false}).waitFor();
  await screen.getByRole('button','File attachment, text-box.docx',{exact:false}).waitFor();
  await screen.getByRole('button','Submit message',{exact:true}).tap();
  await screen.getByText('Extraction read complete.',{exact:false}).waitFor({timeout:60000});
  await screen.getByRole('button','Stop generation',{exact:true}).waitFor({state:'hidden'});
  await app.screenshot('extracted-word-paragraphs');
  const code=JSON.parse(await fs.readFile(path.join(project,'extracted.json'),'utf8'));
  await expect(code).toEqual(['# Real heading\nBody text','Intro. # Box title']);
 } finally { await fs.writeFile(settingsPath,original); }
});
