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

test("Word upload leaves directly hidden text out of the agent sidecar", WEB, async ({ t3, app, screen, browser }) => {
  const document = '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t xml:space="preserve">Budget is </w:t></w:r><w:r><w:rPr><w:vanish/></w:rPr><w:t xml:space="preserve">draft figure </w:t></w:r><w:r><w:t>120 units</w:t></w:r><w:r><w:rPr><w:vanish/></w:rPr><w:t xml:space="preserve"> pending review</w:t></w:r><w:r><w:t>.</w:t></w:r></w:p></w:body></w:document>';
  const bytes = await 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"/><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="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>')
    .file('word/document.xml', document).generateAsync({ type: 'uint8array' });
  const project = await t3.project('budget-review');
  const thread = await t3.thread({ project, title: 'Word attachment extraction', messages: ['Start'] });
  await t3.open(thread);
  await expect(screen.getByText('fixture turn complete', { exact: false })).toBeVisible();
  await browser.evaluate((data: number[]) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]');
    if (!input) throw new Error('Composer file input missing');
    const transfer = new DataTransfer();
    transfer.items.add(new File([new Uint8Array(data)], 'hidden-budget.docx', { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }));
    input.files = transfer.files;
    input.dispatchEvent(new Event('change', { bubbles: true }));
    return null;
  }, Array.from(bytes));
  const attachments = join(T3_HOME, 'userdata', 'attachments');
  let sidecar = '';
  await expect.poll(async () => {
    sidecar = (await readdir(attachments)).find(name => name.endsWith('.docx.txt')) ?? '';
    return sidecar.length > 0;
  }).toBe(true);
  const extracted = await readFile(join(attachments, sidecar), 'utf8');
  // Show the actual server-written sidecar unchanged, without exposing its internal storage path.
  await copyFile(join(attachments, sidecar), join(project, 'agent-extracted-text.txt'));
  await browser.keyboard.press('Control+p');
  await screen.getByPlaceholder('Search files…').fill('agent-extracted-text.txt');
  await screen.getByRole('option', 'agent-extracted-text.txt', { exact: false }).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll('*')) {
      const content = host.shadowRoot?.querySelector('[data-content]');
      if (content?.textContent?.includes('Budget is')) return true;
    }
    return false;
  })).toBe(true);
  await app.screenshot('agent-extracted-text');
  await expect(extracted.trim()).toBe('Budget is 120 units.');
});
