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

async function docx() {
  const ns = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
  const p = (style: string, text: string, level = '') => `<w:p><w:pPr><w:pStyle w:val="${style}"/>${level}</w:pPr><w:r><w:t>${text}</w:t></w:r></w:p>`;
  return new JSZip()
    .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"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/></Types>')
    .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>')
    .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/styles" Target="styles.xml"/></Relationships>')
    .file('word/styles.xml', `<w:styles xmlns:w="${ns}"><w:style w:type="paragraph" w:styleId="ReportSection"><w:name w:val="Report Section"/><w:pPr><w:outlineLvl w:val="1"/></w:pPr></w:style><w:style w:type="paragraph" w:styleId="ReportDetail"><w:name w:val="Report Detail"/><w:basedOn w:val="ReportSection"/></w:style><w:style w:type="paragraph" w:styleId="BodyLevel"><w:name w:val="Body Level"/><w:pPr><w:outlineLvl w:val="9"/></w:pPr></w:style><w:style w:type="paragraph" w:styleId="Kop4"><w:name w:val="heading 4"/><w:basedOn w:val="BodyLevel"/></w:style><w:style w:type="paragraph" w:styleId="Normal"><w:name w:val="Normal"/></w:style></w:styles>`)
    .file('word/document.xml', `<w:document xmlns:w="${ns}"><w:body>${p('ReportSection','Quarterly revenue')}${p('ReportDetail','Revenue by region')}${p('ReportSection','Direct level three','<w:outlineLvl w:val="2"/>')}${p('Kop4','Heading-named style with inherited body level')}${p('Normal','Ordinary body text.')}</w:body></w:document>`)
    .generateAsync({ type: 'uint8array' });
}

test('DOCX attachment extraction preserves custom and inherited outline levels', WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project('outline-demo');
  const thread = await t3.thread({project, title:'DOCX outline extraction', messages:['Start']});
  await t3.open(thread);
  await screen.getByText('fixture turn complete', {exact:false}).waitFor();
  const bytes = await docx();
  // Select a synthetic DOCX through the real composer file input and await its actual HTTP upload.
  await browser.evaluate(async (base64) => {
    const original = XMLHttpRequest.prototype.open;
    const uploaded = new Promise<void>((resolve, reject) => {
      XMLHttpRequest.prototype.open = function (...args) {
        if (String(args[1]).includes('/api/attachments/upload/')) {
          this.addEventListener('load', () => {
            XMLHttpRequest.prototype.open = original;
            if (this.status >= 200 && this.status < 300) resolve(); else reject(new Error(`Upload: ${this.status}`));
          });
        }
        return original.apply(this, args);
      };
    });
    const input = document.querySelector<HTMLInputElement>('input[type="file"]');
    if (!input) throw new Error('No attachment file input');
    const data = new DataTransfer();
    data.items.add(new File([Uint8Array.from(atob(base64), c=>c.charCodeAt(0))], 'outline-styles.docx', {type:'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}));
    input.files = data.files;
    input.dispatchEvent(new Event('change', {bubbles:true}));
    await uploaded;
  }, Buffer.from(bytes).toString('base64'));
  // Show the server-produced sidecar verbatim in the real app's file viewer; replay does not read files.
  const dir = `${T3_HOME}/userdata/attachments`;
  const sidecar = (await readdir(dir)).find(name=>name.endsWith('.docx.txt'));
  if (!sidecar) throw new Error('Upload created no DOCX text sidecar');
  const text = await readFile(`${dir}/${sidecar}`, 'utf8');
  await writeFile(`${project}/extracted-outline.txt`, text);
  await browser.keyboard.press('Control+p');
  await screen.getByPlaceholder('Search files…').fill('extracted-outline.txt');
  await screen.getByRole('option', 'extracted-outline.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 null;
  });
  // Wait for the actual sidecar to render on both commits before capturing the differing prefixes.
  await screen.getByText('extracted-outline.txt', {exact:false}).first().waitFor();
  try {
    await expect.poll(editorText).toContain('Ordinary body text.');
    await app.screenshot('extracted-outline');
    expect(text.trim()).toBe('## Quarterly revenue\n## Revenue by region\n### Direct level three\nHeading-named style with inherited body level\nOrdinary body text.');
  } finally {
    await app.screenshot('outline-result');
  }
});
