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

async function docx(flag: string) {
  return new JSZip()
    .file("[Content_Types].xml", '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>')
    .file("word/document.xml", '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>Retired body text</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val="Plain"/></w:pPr><w:r><w:t>Current instructions</w:t></w:r></w:p></w:body></w:document>')
    .file("word/styles.xml", `<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:style w:type="paragraph" w:styleId="Body" w:default="${flag}"><w:rPr><w:vanish/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Plain"/></w:styles>`)
    .generateAsync({ type: "base64" });
}

async function extractedFiles(dir: string): Promise<string[]> {
  const entries = await readdir(dir, { withFileTypes: true });
  return (await Promise.all(entries.map(async (entry) => {
    const path = `${dir}/${entry.name}`;
    return entry.isDirectory() ? extractedFiles(path) : path.endsWith(".docx.txt") ? [path] : [];
  }))).flat();
}

test("A padded hidden default paragraph style is excluded from attachment extraction", WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("document-review");
    const values: string[] = [];
    for (const [name, flag] of [["padded-default", " 1 "], ["unpadded-default", "1"]]) {
      const thread = await t3.thread({ project, title: name, messages: ["Start"] });
      await t3.open(thread);
      await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
      const previous = new Set(await extractedFiles(`${T3_HOME}/userdata/attachments`).catch(() => []));
      const composer = screen.getByRole("textbox");
      await composer.fill("Quote the text extracted from this attached document.");
      const input = '[data-chat-composer-form] input[type="file"]';
      await browser.locator(input).waitFor({ state: "attached" });
      await browser.evaluate(({ input, data, name }) => {
        const picker = document.querySelector<HTMLInputElement>(input)!;
        const transfer = new DataTransfer();
        const bytes = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
        transfer.items.add(new File([bytes], `${name}.docx`, { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }));
        picker.files = transfer.files;
        picker.dispatchEvent(new Event("change", { bubbles: true }));
        return null;
      }, { input, data: await docx(flag), name });
      await screen.getByRole("button", "Submit message", { exact: true }).tap();
      await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
      const files = await extractedFiles(`${T3_HOME}/userdata/attachments`);
      const created = files.filter((path) => !previous.has(path));
      if (created.length !== 1) throw new Error(`Expected one extracted attachment, found ${created.length}`);
      values.push(await readFile(created[0], "utf8"));
    }
    // Display the real server-generated output, verbatim, through the app's file viewer.
    const report = `SERVER ATTACHMENT EXTRACTION\n\nPadded default flag (w:default=" 1 ")\n${values[0]}\n\nUnpadded control (w:default="1")\n${values[1]}\n`;
    await writeFile(`${project}/extraction-results.txt`, report);
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("extraction-results.txt");
    await screen.getByRole("option", "extraction-results.txt", { exact: false }).tap();
    await screen.getByText("SERVER ATTACHMENT EXTRACTION", { exact: false }).waitFor();
    await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
    await browser.mouse.move(700, 500);
    await app.screenshot("server-extracted-document-text");
    expect(values).toEqual(["Current instructions", "Current instructions"]);
  });
