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

// Synthetic Word-order ruby fixture, including an empty reading in paragraph two.
const docx = "UEsDBBQAAAAIAG6Fe12pAySRKAEAABoEAAARAAAAd29yZC9kb2N1bWVudC54bWzVlM1KxDAQx19l6V2n9uChdAt69LSoL5C2sY00HyRZu3uzFRQRH8GDJz0siFdBXyYi+BYmaON2vYjgYS8zyX9mmMyPJEkTFzyfUsz0aEZrpuJmHFRaixhA5RWmSG1ygZmNHXFJkbZbWULDZSEkz7FShJW0higMt4EiwoI0aeKMF3PnhTPSGZ2+LW5N+5CAWzsrfUxOs3nvJ17ZqUnJRk18gupxUBClJcmmGh8IlOMAXFYlVB/fCr20j4jCvR5FXt9FCh/imV4N1aTopWO0sTdxKgwOo5emMO29ac9Ne226C7sYjAM+19a6dsvT3zy+Pi1+pPtE6DEMyLh+V6a7XH9qX7wsvl8js7zez57/guzFtHfmtFstFcMruU4A/wvaJxXoXyx8/wbpB1BLAwQUAAAACABuhXtdrG4SWp4AAADcAAAAEwAAAFtDb250ZW50X1R5cGVzXS54bWxdj7EOwjAQQ3+lyoraqxgYUNuFHRj4gVNybSOaS5QcBf6eBKQOjJbtZ7m7vQOl6uUWTr2aRcIRIOmZHKbGB+LsjD46lCzjBAH1HSeCfdseQHsWYqmlMNTQXVaK0RqqrhjljI56BU8fDRivHy4nm0xT1elXK8u9whAWq1GsZ1jZ/G3Wfhytpq1faCF6TSlZntzSbI5Dy7uCh6GD76nhA1BLAwQUAAAACABuhXtdYXsvQ4kAAADyAAAACwAAAF9yZWxzLy5yZWxzjc87DgIhEAbgqxAOsLNaWBigstnWeAECwyMujwwY9fZSWKzGwnLmn3x/Rpxx1T2W3EKsjT3Smpvkofd6BGgmYNJtKhXzSFyhpPsYyUPV5qo9wn6eD0BbgyuxNdliJafF7ji7PCv+YxfnosFTMbeEuf+o+LoYsiaPXfJ7IQv2vZ4Gy0EJ+HhRvQBQSwECFAMUAAAACABuhXtdqQMkkSgBAAAaBAAAEQAAAAAAAAAAAAAAgAEAAAAAd29yZC9kb2N1bWVudC54bWxQSwECFAMUAAAACABuhXtdrG4SWp4AAADcAAAAEwAAAAAAAAAAAAAAgAFXAQAAW0NvbnRlbnRfVHlwZXNdLnhtbFBLAQIUAxQAAAAIAG6Fe11hey9DiQAAAPIAAAALAAAAAAAAAAAAAACAASYCAABfcmVscy8ucmVsc1BLBQYAAAAAAwADALkAAADYAgAAAAA=";

test("DOCX extraction keeps each word before its phonetic guide", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Ruby document");
  const thread = await t3.thread({ project, title: "Word phonetic guides", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Read the extracted text of the attached document and quote it exactly, character for character, in a code block. Do not rewrite or correct it.");
  await browser.evaluate((encoded) => {
    const file = new File([Uint8Array.from(atob(encoded), c => c.charCodeAt(0))], "furigana.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
    const data = new DataTransfer(); data.items.add(file);
    const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
    input.files = data.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, docx);
  await screen.getByRole("button", "File attachment, furigana.docx", { exact: false }).waitFor();
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  const attachments = join(T3_HOME, "userdata", "attachments");
  const files = await readdir(attachments, { recursive: true });
  const sidecar = files.find(f => f.endsWith(".docx.txt"));
  if (!sidecar) throw new Error("Upload did not produce a DOCX text sidecar");
  // View the real server output in the app; replay cannot read an arbitrary document.
  await copyFile(join(attachments, sidecar), join(project, "furigana-extracted.txt"));
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("furigana-extracted.txt");
  await screen.getByRole("option", "furigana-extracted.txt", { exact: false }).tap();
  await screen.getByText("furigana-extracted.txt", { exact: true }).first().waitFor();
  const extracted = (await readFile(join(attachments, sidecar), "utf8")).trim();
  await screen.getByText(extracted.split("\n")[0], { exact: false }).first().waitFor();
  await app.screenshot("word-phonetic-guides");
  expect((await readFile(join(attachments, sidecar), "utf8")).trim()).toBe("次は東京(とうきょう)から京都(きょうと)まで。\n京都");
});
