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

async function regions() {
  const w = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
  const r = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
  return new JSZip()
    .file('[Content_Types].xml', '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><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>')
    .file('_rels/.rels', `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${r}/officeDocument" Target="word/document.xml"/></Relationships>`)
    .file('word/document.xml', `<w:document xmlns:w="${w}"><w:body><w:p><w:r><w:t xml:space="preserve">The north region</w:t></w:r><w:r><w:footnoteReference w:id="2"/></w:r><w:r><w:t xml:space="preserve"> is ready. The south region is ready.</w:t></w:r><w:r><w:endnoteReference w:id="2"/></w:r></w:p></w:body></w:document>`)
    .file('word/_rels/document.xml.rels', `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${r}/styles" Target="styles.xml"/><Relationship Id="rId2" Type="${r}/footnotes" Target="footnotes.xml"/><Relationship Id="rId3" Type="${r}/endnotes" Target="endnotes.xml"/></Relationships>`)
    .file('word/styles.xml', `<w:styles xmlns:w="${w}"/>`)
    .file('word/footnotes.xml', `<w:footnotes xmlns:w="${w}"><w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:footnote><w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:r><w:continuationSeparator/></w:r></w:p></w:footnote><w:footnote w:id="2"><w:p><w:r><w:t>Inspect the seals.</w:t></w:r></w:p><w:p><w:r><w:t>Record the inspection.</w:t></w:r></w:p></w:footnote></w:footnotes>`)
    .file('word/endnotes.xml', `<w:endnotes xmlns:w="${w}"><w:endnote w:id="2"><w:p><w:r><w:t>Check power.</w:t></w:r></w:p></w:endnote></w:endnotes>`)
    .generateAsync({ type: 'base64' });
}

test('DOCX attachment text includes footnotes and endnotes inline', WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project('regions');
  const thread = await t3.thread({ project, title: 'DOCX attachment text', messages: ['Inspect the server extraction: :codex-file-citation{path="attachment-text.md"}'] });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await screen.getByText('first fixture turn complete', { exact: false }).waitFor();
  const composer = screen.getByRole('textbox');
  await composer.fill('Read regions.docx, including its footnote and endnote.');
  await browser.evaluate((base64) => {
    const bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
    const clipboardData = new DataTransfer();
    clipboardData.items.add(new File([bytes], 'regions.docx', { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }));
    const editor = document.querySelector('[contenteditable="true"]');
    if (!editor) throw new Error('No composer');
    editor.dispatchEvent(new ClipboardEvent('paste', { clipboardData, bubbles: true, cancelable: true }));
    return null;
  }, await regions());
  await screen.getByRole('button', 'File attachment, regions.docx', { exact: false }).waitFor();
  await composer.tap();
  await browser.keyboard.press('Enter');
  await screen.getByText('second fixture turn complete', { exact: false }).waitFor();
  const attachments = join(T3_HOME, 'userdata', 'attachments');
  const entries = await readdir(attachments, { recursive: true });
  const extracted = entries.find(p => p.endsWith('.docx.txt'));
  if (!extracted) throw new Error('Upload completed without extracted .docx.txt');
  const text = await readFile(join(attachments, extracted), 'utf8');
  await writeFile(join(project, 'attachment-text.md'), '# Server-extracted attachment text\n\nSource: regions.docx, uploaded through the composer.\n\nThe block below is the unmodified .docx.txt supplied to agents.\n\n```text\n' + text + '\n```\n');
  await screen.getByRole('button', /^Agent Inspect/).tap();
  await screen.getByRole('link', /^attachment-text\.md/).tap();
  await screen.getByRole('button', 'Show rendered markdown').tap();
  await screen.getByText('Server-extracted attachment text', { exact: true }).waitFor();
  await screen.getByRole('button', 'Maximize panel', { exact: true }).tap();
  await screen.getByText('The north region', { exact: false }).waitFor();
  await app.screenshot('docx-extracted-text');
  expect(text).toContain('The north region[Note: Inspect the seals.\nRecord the inspection.] is ready. The south region is ready.[Note: Check power.]');
});
