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

const zip = async (parts: Record<string,string>) => {
  const z = new JSZip();
  for (const [name, text] of Object.entries(parts)) z.file(name,text);
  return z.generateAsync({type:"base64"});
};
test("Document extraction preserves block boundaries after inline text", WEB, async ({t3,app,browser,screen}) => {
 const epub = await zip({
  "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
  "book.opf": '<package><manifest><item id="a" href="a.xhtml"/></manifest><spine><itemref idref="a"/></spine></package>',
  "a.xhtml": '<html xmlns="http://www.w3.org/1999/xhtml"><body><div>Intro<p>Body paragraph</p></div><ul><li>Summary<p>Details</p></li></ul><div>Intro<h2>Section Title</h2></div><div>First<p>Second</p></div><table><tr><td>First<p>Second</p></td><td>Neighbor</td></tr></table></body></html>'
 });
 const docx = await zip({"word/document.xml": '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>Before</w:t></w:r><w:r><w:drawing><w:txbxContent><w:p><w:r><w:t>Box text</w:t></w:r></w:p></w:txbxContent></w:drawing></w:r><w:r><w:t>After</w:t></w:r></w:p></w:body></w:document>'});
 const project = await t3.project("documents");
 const thread = await t3.thread({project,title:"Document extraction",messages:["Start"]});
 await t3.open(thread);
 await screen.getByRole("textbox").fill("Inspect attached document structure");
 await browser.evaluate(({epub,docx}) => {
  const transfer = new DataTransfer();
  for(const [name,data,type] of [["chapter.epub",epub,"application/epub+zip"],["textbox.docx",docx,"application/vnd.openxmlformats-officedocument.wordprocessingml.document"]]) transfer.items.add(new File([Uint8Array.from(atob(data), c=>c.charCodeAt(0))],name,{type}));
  const input = document.querySelector<HTMLInputElement>('input[type="file"]');
  if(!input) throw Error("No file attachment input");
  input.files = transfer.files;
  input.dispatchEvent(new Event("change",{bubbles:true}));
 },{epub,docx});
 await screen.getByRole("button","Submit message",{exact:true}).tap();
 // The server creates sidecars during attachment upload/claim, independently of the replay reply.
 const files = async () => (await readdir(T3_HOME,{recursive:true})).filter(p=>/\.(epub|docx)\.txt$/.test(p));
 let paths: string[] = [];
 for(let n=0;n<100;n++) { paths = await files(); if(paths.some(p=>p.endsWith('.epub.txt')) && paths.some(p=>p.endsWith('.docx.txt'))) break; await new Promise(r=>setTimeout(r,100)); }
 const read = async (ext:string) => readFile(`${T3_HOME}/${paths.find(p=>p.endsWith(ext+'.txt'))}`,"utf8");
 const extractedEpub=await read('.epub'), extractedDocx=await read('.docx');
 const report = `EPUB — server-generated extracted text\n${extractedEpub}\n\nDOCX — server-generated extracted text\n${extractedDocx}\n`;
 await writeFile(`${project}/extracted-text.txt`,report);
 await browser.keyboard.press("Control+p");
 await screen.getByPlaceholder("Search files…").fill("extracted-text.txt");
 await screen.getByRole("option","extracted-text.txt",{exact:false}).tap();
 const editorText=()=>browser.evaluate(()=>{for(const host of document.querySelectorAll('*')){const content=host.shadowRoot?.querySelector('[data-content]'); if(content)return content.textContent;}return '';});
 for(let n=0;n<100;n++){if((await editorText())?.includes('DOCX'))break;await new Promise(r=>setTimeout(r,100));}
 await app.screenshot("extracted-document-text");
 expect(extractedEpub).toContain("Intro\nBody paragraph");
 expect(extractedEpub).toContain("Summary\nDetails");
 expect(extractedEpub).toContain("Intro\n## Section Title");
 expect(extractedEpub).toContain("First\nSecond");
 expect(extractedEpub).toContain("First Second\tNeighbor");
 expect(extractedDocx).toBe("Before\nBox text\nAfter");
});
