import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("EPUB upload separates ruby readings in extracted attachment text", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("epub-review");
  const thread = await t3.thread({project, title:"EPUB attachment text", messages:["Start"]});
  await t3.open(thread);
  await screen.getByRole("button", "Attach files", {exact:true}).waitFor();
  const epub = Buffer.from(await (await fetch("https://github.com/IDPF/epub3-samples/releases/download/20230704/kusamakura-preview.epub")).arrayBuffer());
  await browser.evaluate((base64) => {
    const originalSend = XMLHttpRequest.prototype.send;
    (window as any).epubUploadFinished = new Promise<void>((resolve, reject) => {
      XMLHttpRequest.prototype.send = function(body) {
        if (body instanceof Blob && body.size > 9000000) {
          this.addEventListener("load", () => this.status >= 200 && this.status < 300 ? resolve() : reject(new Error("Upload HTTP " + this.status)));
          this.addEventListener("error", () => reject(new Error("Upload network error")));
          XMLHttpRequest.prototype.send = originalSend;
        }
        return originalSend.call(this, body);
      };
    });
    const input = document.querySelector('form[data-chat-composer-form] input[type="file"]') as HTMLInputElement;
    if (!input) throw new Error("No attachment file input");
    const transfer = new DataTransfer();
    transfer.items.add(new File([Uint8Array.from(atob(base64), c=>c.charCodeAt(0))], "kusamakura-preview.epub", {type:"application/epub+zip"}));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", {bubbles:true}));
  }, epub.toString("base64"));
  await screen.getByRole("button", "File attachment, kusamakura-preview.epub, 9.5 MB", {exact:true}).waitFor({timeout:120000});
  await browser.evaluate(async () => { await (window as any).epubUploadFinished; return null; });
  // The chip drops its progress suffix only after the upload response; the server writes the sidecar before replying.
  const files = await fs.readdir(path.join(T3_HOME,"userdata"), {recursive:true});
  const sidecar = files.find(f=>f.endsWith(".epub.txt"));
  if (!sidecar) throw new Error("Upload has not produced its EPUB text sidecar");
  const text = await fs.readFile(path.join(T3_HOME,"userdata",sidecar),"utf8");
  const excerpt = text.split("\n").filter(line=>line.includes("山路") || line.includes("智")).join("\n\n");
  await fs.writeFile(path.join(project,"extracted-attachment-text.txt"), "Actual text from the EPUB upload sidecar\n\n"+excerpt);
  await app.screenshot("uploaded-epub");
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-attachment-text.txt");
  await screen.getByRole("option","extracted-attachment-text.txt",{exact:false}).tap();
  await screen.getByText("Actual text from the EPUB upload sidecar",{exact:false}).waitFor();
  await app.screenshot("extracted-ruby-text");
  expect(text).toContain("山路(やまみち)");
});
