/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const cases = [
  { name: "rowspan", body: '<h1>Sales</h1><table><tr><th>Region</th><th>Month</th><th>Revenue</th></tr><tr><td rowspan="2">North</td><td>June</td><td>400</td></tr><tr><td>July</td><td>520</td></tr></table>', note: 'North spans 2 rows. Expected July in Month (2), 520 in Revenue (3).' },
  { name: "colspan", body: '<table><tr><th>Region</th><th>Month</th><th>Revenue</th></tr><tr><td colspan="2">North / June</td><td>400</td></tr></table>', note: 'North / June spans 2 columns. Expected 400 in Revenue (3).' },
  { name: "wide-heading", body: '<table><tr><td colspan="511">Lead</td><th colspan="1000">Wide heading</th></tr><tr><td>Next row</td></tr></table><p>After the table</p>', note: 'Wide heading starts at column 512, spans 1000. Keep heading and following content.' },
  { name: "past-limit", body: '<table><tr><td colspan="512">Heading</td><td>Out of range</td></tr></table><p>After the table</p>', note: 'Text starts at column 513. Keep Heading; truncate before Out of range and following content.' },
];
function epub(body: string) {
  return execFileSync("python3", ["-c", `import io,sys,zipfile
b=io.BytesIO()
with zipfile.ZipFile(b,'w') as z:
 z.writestr('mimetype','application/epub+zip')
 z.writestr('META-INF/container.xml','<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0"><rootfiles><rootfile full-path="book.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
 z.writestr('book.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">synthetic</dc:identifier><dc:title>Sales</dc:title><dc:language>en</dc:language></metadata><manifest><item id="c" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="c"/></spine></package>')
 z.writestr('chapter.xhtml','<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Sales</title></head><body>'+sys.argv[1]+'</body></html>')
sys.stdout.buffer.write(b.getvalue())`, body]);
}

test("EPUB merged cells retain column positions and bounded headings", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("EPUB-evidence");
  const thread = await t3.thread({ project, title: "EPUB extraction", messages: ["Inspect synthetic EPUB extraction"] });
  const results: string[] = [];
  for (const item of cases) {
    const bytes = epub(item.body);
    writeFileSync(join(project, `${item.name}.epub`), bytes);
    const uploaded = await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      return yield* client["attachments.createUploadUrl"]({ type: "file", name: `${item.name}.epub`, mimeType: "application/epub+zip", sizeBytes: bytes.length });
    }).pipe(Effect.scoped));
    const response = await fetch(`${app.baseUrl}${uploaded.relativeUrl}`, { method: "POST", body: bytes });
    if (!response.ok) throw new Error(`Upload failed: ${response.status} ${await response.text()}`);
    const output = readFileSync(join(T3_HOME, "userdata", "attachments", `${uploaded.attachmentId}.epub.txt`), "utf8");
    results.push(output);
    writeFileSync(join(project, `${item.name}.extracted.txt`), output);
    const visible = execFileSync("cat", ["-A"], { input: output, encoding: "utf8" });
    const rows = output.split("\n").filter(line => line.includes("\t")).map(line => line.split("\t").map((cell, i) => cell ? `${i + 1}: ${cell}` : "").filter(Boolean).join(" | "));
    const shortOutput = visible.split("\n").map(line => line.length > 150 ? line.replace(/(?:\^I){3,}/g, s => `[${s.length / 2} TABs]`) : line).join("\n");
    writeFileSync(join(project, `${item.name}-evidence.txt`), [
      `EPUB SERVER EXTRACTION: ${item.name}`, "", item.note, "", "Actual cat -A output (^I = TAB, $ = newline):", shortOutput,
      "", "Actual populated fields (1-based column indexes):", ...rows,
      "", `Heading retained: ${output.includes(item.name === "wide-heading" ? "Wide heading" : "Heading")}`,
      `Following content retained: ${output.includes("After the table")}`,
      `Truncation marker present: ${output.includes("[Extracted text truncated")}`,
      "", "Source: real attachment upload endpoint; server-created .epub.txt.", "Long TAB runs abbreviated above; complete output is in .extracted.txt."
    ].join("\n"));
  }
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  for (const item of cases) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(`${item.name}-evidence.txt`);
    await screen.getByRole("option", `${item.name}-evidence.txt`, { exact: false }).tap();
    await screen.getByText(`EPUB SERVER EXTRACTION: ${item.name}`, { exact: false }).waitFor();
    await screen.getByPlaceholder("Search files…").waitFor({ state: "hidden" });
    if (item.name === "rowspan") {
      await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
      await screen.getByRole("button", "Hide file explorer", { exact: true }).tap();
    }
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {})));
      (document.activeElement as HTMLElement)?.blur();
    });
    await app.screenshot(item.name);
  }
  expect({
    rowspan: results[0].includes("North\tJune\t400\n\tJuly\t520"),
    colspan: results[1].includes("North / June\t\t400"),
    wideHeading: results[2].includes("Lead" + "\t".repeat(511) + "Wide heading") && results[2].includes("After the table") && !results[2].includes("[Extracted text truncated"),
    pastLimit: results[3].includes("Heading") && results[3].includes("[Extracted text truncated") && !results[3].includes("Out of range") && !results[3].includes("After the table"),
  }).toEqual({ rowspan: true, colspan: true, wideHeading: true, pastLimit: true });
});
