/// <reference lib="dom" />
import { expect } from "e2e";
import * as fs from "node:fs/promises";
import { test, WEB } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("EPUB header and footer boundaries survive attachment extraction", WEB, async ({ t3, app, browser, screen }) => {
 const project = await t3.project("Harbor-guide", {"extracted.txt":"Waiting for upload"});
 const thread = await t3.thread({ project, title:"Harbor guide extraction", model:"multi-turn", messages:['See :codex-file-citation{path="extracted.txt" line_range_start="1"}'] });
 await t3.open(thread);
 await screen.getByRole("button", "Attach files", {exact:true}).waitFor({state:"visible"});
 await browser.evaluate((data) => {
  const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
  const transfer = new DataTransfer();
  transfer.items.add(new File([Uint8Array.from(atob(data), c => c.charCodeAt(0))], "harbor-guide.epub", {type:"application/epub+zip"}));
  input.files = transfer.files;
  input.dispatchEvent(new Event("change", {bubbles:true}));
 }, "UEsDBBQAAAAAAI6Gel1vYassFAAAABQAAAAIAAAAbWltZXR5cGVhcHBsaWNhdGlvbi9lcHViK3ppcFBLAwQUAAAAAACOhnpdyRd0PU4AAABOAAAAFgAAAE1FVEEtSU5GL2NvbnRhaW5lci54bWw8Y29udGFpbmVyPjxyb290ZmlsZXM+PHJvb3RmaWxlIGZ1bGwtcGF0aD0iYm9vay5vcGYiLz48L3Jvb3RmaWxlcz48L2NvbnRhaW5lcj5QSwMEFAAAAAAAjoZ6XbiN1kadAAAAnQAAAAgAAABib29rLm9wZjxwYWNrYWdlPjxtYW5pZmVzdD48aXRlbSBpZD0iY2hhcHRlciIgaHJlZj0iY2hhcHRlci54aHRtbCIgbWVkaWEtdHlwZT0iYXBwbGljYXRpb24veGh0bWwreG1sIi8+PC9tYW5pZmVzdD48c3BpbmU+PGl0ZW1yZWYgaWRyZWY9ImNoYXB0ZXIiLz48L3NwaW5lPjwvcGFja2FnZT5QSwMEFAAAAAAAjoZ6XWkgi/oiAQAAIgEAAA0AAABjaGFwdGVyLnhodG1sPGh0bWwgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGh0bWwiPjxib2R5PjxzZWN0aW9uPlVwZGF0ZWQgdGltZXRhYmxlLjxoZWFkZXI+PHN0cm9uZz5IYXJib3IgZGVwYXJ0dXJlczwvc3Ryb25nPjwvaGVhZGVyPkNvbmZpcm0geW91ciBiZXJ0aC48Zm9vdGVyPlNvdXJjZTogSGFyYm9yIE9mZmljZTwvZm9vdGVyPktlZXAgdGhpcyBndWlkZS48L3NlY3Rpb24+PHNlY3Rpb24+S2VlcCA8aGVhZGVyPjwvaGVhZGVyPjxmb290ZXI+PC9mb290ZXI+cmVhZGluZy48L3NlY3Rpb24+PC9ib2R5PjwvaHRtbD5QSwECFAMUAAAAAACOhnpdb2GrLBQAAAAUAAAACAAAAAAAAAAAAAAAgAEAAAAAbWltZXR5cGVQSwECFAMUAAAAAACOhnpdyRd0PU4AAABOAAAAFgAAAAAAAAAAAAAAgAE6AAAATUVUQS1JTkYvY29udGFpbmVyLnhtbFBLAQIUAxQAAAAAAI6Gel24jdZGnQAAAJ0AAAAIAAAAAAAAAAAAAACAAbwAAABib29rLm9wZlBLAQIUAxQAAAAAAI6Gel1pIIv6IgEAACIBAAANAAAAAAAAAAAAAACAAX8BAABjaGFwdGVyLnhodG1sUEsFBgAAAAAEAAQA6wAAAMwCAAAAAA==");
 await screen.getByText("harbor-guide.epub", {exact:true}).waitFor({state:"visible"});
 const composer = screen.getByRole("textbox");
 await composer.pressSequentially("Read the extracted attachment text verbatim.");
 await composer.press("Enter");
 await screen.getByText("second fixture turn complete", {exact:false}).waitFor({state:"visible"});
 const files = await fs.readdir(`${T3_HOME}/userdata/attachments`, {recursive:true});
 const name = files.find(f => f.endsWith(".epub.txt") && !f.includes("pending-"));
 if (!name) throw new Error("Claimed EPUB extraction missing: " + files.join(","));
 const text = await fs.readFile(`${T3_HOME}/userdata/attachments/${name}`, "utf8");
 await fs.writeFile(`${project}/extracted.txt`, text);
 await screen.getByRole("button", /^Agent See/).tap();
 await screen.getByRole("link", /^extracted\.txt/).tap();
 await browser.locator('[data-file-crumb]').first().waitFor({state:"visible"});
 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("Harbor departures");
 await app.screenshot("extracted-epub-text");
 expect(text).toBe("## Chapter 1\nUpdated timetable.\nHarbor departures\nConfirm your berth.\nSource: Harbor Office\nKeep this guide.\nKeep reading.");
});
