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

async function sidecars(dir: string): Promise<string[]> {
  const entries = await readdir(dir, { withFileTypes: true });
  const lists = await Promise.all(entries.map(e => e.isDirectory() ? sidecars(join(dir,e.name)) : Promise.resolve(e.name.endsWith('.epub.txt') ? [join(dir,e.name)] : [])));
  return lists.flat();
}

test("EPUB attachment separates ruby readings", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("EPUB-proof", {"extracted-attachment.txt":"Waiting for upload extraction"});
  const thread = await t3.thread({project, title:"EPUB ruby attachment", messages:['See :codex-file-citation{path="extracted-attachment.txt" line_range_start="1"}']});
  await t3.open(thread);
  await expect(screen.getByRole("button", "Attach files")).toBeVisible();
  const download = await fetch('https://github.com/IDPF/epub3-samples/releases/download/20230704/kusamakura-preview.epub');
  if (!download.ok) throw new Error(`EPUB download failed: ${download.status}`);
  const bytes = Buffer.from(await download.arrayBuffer());
  await browser.evaluate((base64) => {
    const input = document.querySelector('input[type="file"]') as HTMLInputElement;
    if (!input) throw new Error('Attachment input missing');
    const data = new DataTransfer();
    data.items.add(new File([Uint8Array.from(atob(base64),c=>c.charCodeAt(0))], 'kusamakura-preview.epub', {type:'application/epub+zip'}));
    input.files=data.files;
    input.dispatchEvent(new Event('change',{bubbles:true}));
  }, bytes.toString('base64'));
  let extracted = '';
  await expect.poll(async () => {
    const files = await sidecars(T3_HOME);
    extracted = files.length ? await readFile(files[0], 'utf8') : '';
    return extracted.includes('山路');
  }, {timeout:30000}).toBe(true);
  const start = extracted.indexOf('## 一');
  await writeFile(join(project,'extracted-attachment.txt'), 'kusamakura-preview.epub — actual upload extraction\n\n'+extracted.slice(start,start+800));
  await screen.getByRole('button', /^Agent See/).tap();
  await screen.getByRole('link', /^extracted-attachment\.txt/).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll('*')) {
      const content = host.shadowRoot?.querySelector('[data-content]');
      if (content) return content.textContent ?? '';
    }
    return '';
  })).toContain('actual upload extraction');
  await app.screenshot('epub-ruby-extracted-attachment');
  expect(extracted).toContain('山路(やまみち)を登りながら');
});
