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

async function findSidecar(dir: string): Promise<string | undefined> {
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const path = join(dir, entry.name);
    if (entry.isDirectory()) { const found = await findSidecar(path); if (found) return found; }
    else if (entry.name.endsWith('.epub.txt')) return path;
  }
}

test("EPUB contact details remain separate from surrounding prose", WEB, async ({ t3, app, browser, screen }) => {
  const epub = await new JSZip()
    .file('mimetype', 'application/epub+zip')
    .file('META-INF/container.xml', '<?xml version="1.0"?><container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0"><rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
    .file('OEBPS/content.opf', '<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">harbor</dc:identifier><dc:title>Harbor Notes</dc:title><dc:language>en</dc:language></metadata><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>')
    .file('OEBPS/chapter.xhtml', '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Chapter 1</title></head><body><div>Contact the duty editor.<address><strong>Harbor Office</strong><br/>Pier 7</address>Include your reference.</div><div>Wait <address></address>here.</div></body></html>')
    .generateAsync({type:'base64'});
  const project = await t3.project('harbor-notes');
  const thread = await t3.thread({project, title:'EPUB contact text', messages:['Start']});
  await t3.open(thread);
  await screen.getByRole('textbox').fill('Read the extracted-text file for the attached EPUB and quote its contents verbatim, preserving line breaks.');
  await browser.evaluate((base64: string) => {
    const input = document.querySelector<HTMLInputElement>('form[data-chat-composer-form] input[type="file"]');
    if (!input) throw new Error('Composer file input missing');
    const transfer = new DataTransfer();
    transfer.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], 'harbor-notes.epub', {type:'application/epub+zip'}));
    input.files = transfer.files;
    input.dispatchEvent(new Event('change', {bubbles:true}));
  }, epub);
  // Upload completion is observed from the real server's sidecar, without substituting extraction.
  let sidecar: string | undefined;
  await expect.poll(async () => { sidecar = await findSidecar(T3_HOME); return Boolean(sidecar); }, {timeout:60000}).toBe(true);
  const text = await readFile(sidecar!, 'utf8');
  await writeFile(join(project, 'harbor-notes.epub.txt'), text);
  await screen.getByRole('button', 'Toggle terminal drawer').tap();
  const terminal = screen.getByRole('textbox', 'Terminal input');
  await expect(terminal).toHaveAttribute('data-workspace-focus-default', '');
  await terminal.focus();
  await browser.keyboard.type("PS1='harbor> '; clear; cat harbor-notes.epub.txt; printf '\\n'; touch capture-ready\n");
  await expect.poll(async () => { try { await readFile(join(project, 'capture-ready')); return true; } catch { return false; } }).toBe(true);
  await app.screenshot('extracted-epub-contact-text');
  expect(text).toContain('Contact the duty editor.\nHarbor Office\nPier 7\nInclude your reference.');
  expect(text).toContain('Wait here.');
});
