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

async function epub(nested: boolean) {
  const table = '<table><tr><th>Month</th><th>Revenue</th></tr><tr><td>June</td><td>400</td></tr></table>';
  return new JSZip()
    .file('mimetype', 'application/epub+zip', {compression: 'STORE'})
    .file('META-INF/container.xml', '<container><rootfile full-path="book.opf"/></container>')
    .file('book.opf', '<package version="3.0"><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>')
    .file('chapter.xhtml', `<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Chapter 1</title></head><body>${nested ? `<div>Quarterly revenue${table}</div>` : `<div>Quarterly revenue</div>${table}`}</body></html>`)
    .generateAsync({type: 'base64'});
}

test('EPUB extraction separates prose from the first table row', WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project('Revenue');
  const thread = await t3.thread({project, title: 'EPUB table extraction', messages: ['Start']});
  await t3.open(thread);
  await screen.getByRole('button', 'Attach files', {exact: true}).waitFor();
  const files = [{name: 'revenue-nested.epub', data: await epub(true)}, {name: 'revenue-sibling.epub', data: await epub(false)}];
  await browser.evaluate((items) => {
    const transfer = new DataTransfer();
    for (const item of items) transfer.items.add(new File([Uint8Array.from(atob(item.data), c => c.charCodeAt(0))], item.name, {type: 'application/epub+zip'}));
    const input = document.querySelector('input[type="file"]') as HTMLInputElement;
    if (!input) throw new Error('No composer attachment input');
    input.files = transfer.files;
    input.dispatchEvent(new Event('change', {bubbles: true}));
    return null;
  }, files);
  await screen.getByText('revenue-nested.epub', {exact: true}).first().waitFor();
  await screen.getByText('revenue-sibling.epub', {exact: true}).first().waitFor();
  await screen.getByRole('textbox').fill('For each attachment, print the full contents of its extracted-text file verbatim inside a code block, preserving line breaks. Use cat; do not paraphrase.');
  await screen.getByRole('textbox').press('Enter');
  await screen.getByText('second fixture turn complete', {exact: false}).waitFor();
  const dir = `${T3_HOME}/userdata/attachments`;
  const read = () => {
    try { return readdirSync(dir).filter(f => f.endsWith('.epub.txt')).sort().map(f => readFileSync(`${dir}/${f}`, 'utf8')); } catch { return []; }
  };
  await expect.poll(() => read().length, {timeout: 60000}).toBe(2);
  const names = readdirSync(dir).filter(f => f.endsWith('.epub.txt')).sort();
  const records = await Promise.all(names.map(async name => {
    const archive = await JSZip.loadAsync(readFileSync(`${dir}/${name.slice(0, -4)}`));
    const chapter = await archive.file('chapter.xhtml')!.async('string');
    return {name: chapter.includes('revenue<table>') ? 'revenue-nested.epub' : 'revenue-sibling.epub', text: readFileSync(`${dir}/${name}`, 'utf8')};
  }));
  records.sort((a,b) => a.name.localeCompare(b.name));
  const contents = records.map(record => record.text);
  writeFileSync(`${project}/extracted.txt`, 'EPUB extracted-text files (verbatim)\n\n' + records.map(record => `${record.name}:\n${record.text}\n`).join('\n'));
  await screen.getByRole('button', 'Toggle terminal drawer').tap();
  const terminal = screen.getByLabel('Terminal input');
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("printf '\\033c'; PS1='$ '; cat extracted.txt");
    await browser.keyboard.press('Enter');
    await browser.evaluate(() => {
      delete document.body.dataset.terminalCopy;
      window.addEventListener('copy', event => { document.body.dataset.terminalCopy = event.clipboardData?.getData('text/plain') ?? ''; }, {once: true});
      return null;
    });
    await browser.keyboard.press('Control+Shift+A');
    await browser.keyboard.press('Control+Shift+C');
    return browser.evaluate(() => document.body.dataset.terminalCopy ?? '');
  }, {timeout: 30000}).toContain('Quarterly revenue');
  await browser.keyboard.press('ArrowRight');
  await app.screenshot('epub-extracted-text');
  for (const text of contents) expect(text).toContain('Quarterly revenue\nMonth\tRevenue\nJune\t400');
});
