/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

async function report() {
  const zip = new JSZip();
  const ns = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
  zip.file('[Content_Types].xml', '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>');
  zip.file('_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>');
  zip.file('word/document.xml', `<w:document xmlns:w="${ns}"><w:body>${Array.from({length:5},(_,i)=>`<w:p><w:r><w:t>Quarterly report paragraph ${i+1}: field survey findings are summarised here.</w:t></w:r></w:p>`).join('')}<w:p><w:r><w:t>See the survey results.</w:t></w:r><w:r><w:footnoteReference w:id="1"/></w:r></w:p></w:body></w:document>`);
  zip.file('word/_rels/document.xml.rels', '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml"/></Relationships>');
  const para = '<w:p>' + '<w:r><w:rPr><w:b/></w:rPr><w:t>Sample recorded.</w:t></w:r><w:r><w:t> Survey note.</w:t></w:r>'.repeat(5) + '</w:p>';
  zip.file('word/footnotes.xml', `<w:footnotes xmlns:w="${ns}"><w:footnote w:id="1">${para.repeat(6500)}</w:footnote></w:footnotes>`);
  return zip.generateAsync({type:'base64', compression:'DEFLATE'});
}
async function extracted() {
  const root = path.join(T3_HOME, 'userdata', 'attachments');
  const files = await fs.readdir(root, {recursive:true});
  const name = files.find(f=>f.endsWith('.docx.txt'));
  return name ? fs.readFile(path.join(root,name),'utf8') : null;
}
test('A large footnote retains the attached report body', WEB, async ({t3,app,browser,screen})=>{
  const project = await t3.project('survey-report');
  const thread = await t3.thread({project,title:'Survey report',messages:['Start'], model:'showcase'});
  await t3.open(thread);
  await screen.getByTestId('composer-editor').waitFor();
  await browser.evaluate((payload:string)=>{
    const bytes=Uint8Array.from(atob(payload),c=>c.charCodeAt(0));
    const input=document.querySelector('form[data-chat-composer-form] input[type="file"]') as HTMLInputElement;
    if(!input) throw new Error('Attachment input missing');
    const transfer=new DataTransfer();
    transfer.items.add(new File([bytes],'survey-report.docx',{type:'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}));
    input.files=transfer.files; input.dispatchEvent(new Event('change',{bubbles:true}));
  },await report());
  await screen.getByTestId('composer-editor').fill('Summarise the attached report.');
  await screen.getByRole('button','Submit message',{exact:true}).tap();
  // Wait for the actual server's extraction artifact, then show it in the app file viewer.
  let text:string|null=null;
  await expect.poll(async()=>{text=await extracted();return text!==null;}).toBe(true);
  await fs.writeFile(path.join(project,'extracted-report.txt'),text!);
  await browser.keyboard.press('Control+p');
  await screen.getByPlaceholder('Search files…').fill('extracted-report.txt');
  await screen.getByRole('option','extracted-report.txt',{exact:false}).tap();
  await screen.getByText('[Extracted text truncated at document extraction limits.]',{exact:false}).first().waitFor();
  await app.screenshot('extracted-report-body');
  expect(text).toContain('Quarterly report paragraph 1: field survey findings are summarised here.');
  expect(text).toContain('Quarterly report paragraph 5: field survey findings are summarised here.');
  expect(text).toContain('See the survey results.');
});
