import { expect } from "e2e";
import { readdir, readFile, copyFile } from "node:fs/promises";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";
const EPUB = "UEsDBBQAAAAAALR7eV1vYassFAAAABQAAAAIAAAAbWltZXR5cGVhcHBsaWNhdGlvbi9lcHViK3ppcFBLAwQUAAAAAAC0e3ld6vhN4sIAAADCAAAAFgAAAE1FVEEtSU5GL2NvbnRhaW5lci54bWw8Y29udGFpbmVyIHhtbG5zPSJ1cm46b2FzaXM6bmFtZXM6dGM6b3BlbmRvY3VtZW50OnhtbG5zOmNvbnRhaW5lciIgdmVyc2lvbj0iMS4wIj48cm9vdGZpbGVzPjxyb290ZmlsZSBmdWxsLXBhdGg9ImNvbnRlbnQub3BmIiBtZWRpYS10eXBlPSJhcHBsaWNhdGlvbi9vZWJwcy1wYWNrYWdlK3htbCIvPjwvcm9vdGZpbGVzPjwvY29udGFpbmVyPlBLAwQUAAAAAAC0e3ldTg2shYUBAACFAQAACwAAAGNvbnRlbnQub3BmPHBhY2thZ2UgeG1sbnM9Imh0dHA6Ly93d3cuaWRwZi5vcmcvMjAwNy9vcGYiIHZlcnNpb249IjMuMCIgdW5pcXVlLWlkZW50aWZpZXI9ImlkIj48bWV0YWRhdGEgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj48ZGM6aWRlbnRpZmllciBpZD0iaWQiPnByb29mPC9kYzppZGVudGlmaWVyPjxkYzp0aXRsZT5DaGVja2xpc3Q8L2RjOnRpdGxlPjxkYzpsYW5ndWFnZT5lbjwvZGM6bGFuZ3VhZ2U+PC9tZXRhZGF0YT48bWFuaWZlc3Q+PGl0ZW0gaWQ9ImNoIiBocmVmPSJjaGFwdGVyLnhodG1sIiBtZWRpYS10eXBlPSJhcHBsaWNhdGlvbi94aHRtbCt4bWwiLz48L21hbmlmZXN0PjxzcGluZT48aXRlbXJlZiBpZHJlZj0iY2giLz48L3NwaW5lPjwvcGFja2FnZT5QSwMEFAAAAAAAtHt5XTK5GKO4AAAAuAAAAA0AAABjaGFwdGVyLnhodG1sPGh0bWwgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGh0bWwiPjxoZWFkPjx0aXRsZT5DaGFwdGVyIDE8L3RpdGxlPjwvaGVhZD48Ym9keT48aDE+Q2hlY2tsaXN0PC9oMT48b2w+PGxpPkJlZm9yZSBib2FyZGluZzx1bD48bGk+Q2hlY2sgcGFzc3BvcnRzPC9saT48L3VsPjwvbGk+PC9vbD48L2JvZHk+PC9odG1sPlBLAQIUAxQAAAAAALR7eV1vYassFAAAABQAAAAIAAAAAAAAAAAAAACAAQAAAABtaW1ldHlwZVBLAQIUAxQAAAAAALR7eV3q+E3iwgAAAMIAAAAWAAAAAAAAAAAAAACAAToAAABNRVRBLUlORi9jb250YWluZXIueG1sUEsBAhQDFAAAAAAAtHt5XU4NrIWFAQAAhQEAAAsAAAAAAAAAAAAAAIABMAEAAGNvbnRlbnQub3BmUEsBAhQDFAAAAAAAtHt5XTK5GKO4AAAAuAAAAA0AAAAAAAAAAAAAAIAB3gIAAGNoYXB0ZXIueGh0bWxQSwUGAAAAAAQABADuAAAAwQMAAAAA";
async function extracted(dir: string): Promise<string | undefined> {
  for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
    const path = join(dir, entry.name);
    if (entry.isDirectory()) { const found = await extracted(path); if(found) return found; }
    else if (entry.name.endsWith(".epub.txt")) return path;
  }
}
test("EPUB upload separates a parent introduction from its nested item", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("epub-proof");
  const thread = await t3.thread({project, title: "Nested EPUB attachment", messages: ["first"]});
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Print the extracted text of the attached EPUB verbatim.");
  await browser.evaluate((base64: string) => {
    const input = document.querySelector('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))], "nested-list.epub", {type:"application/epub+zip"}));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", {bubbles:true}));
  }, EPUB);
  await screen.getByRole("button", "File attachment, nested-list.epub", {exact:false}).waitFor();
  let path: string | undefined;
  for(let i=0;i<300;i++) { path = await extracted(T3_HOME); if(path) break; await new Promise(r=>setTimeout(r,100)); }
  if(!path) throw new Error("Upload did not create extracted EPUB text");
  const text = await readFile(path,"utf8");
  await copyFile(path, join(project,"extracted.txt"));
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await input.waitFor();
  await input.focus();
  await browser.keyboard.type("PS1='' ; clear; printf 'EPUB attachment: extracted text\n\n'; cat extracted.txt; printf '\n'; touch shown; cat >/dev/null\n");
  for(let i=0;i<100;i++) { if(await readFile(join(project,"shown"),"utf8").then(()=>true,()=>false)) break; await new Promise(r=>setTimeout(r,100)); }
  await app.screenshot("nested-epub-extracted-text");
  expect(text).toContain("Before boarding\nCheck passports");
});
