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

const notebook = JSON.stringify({
  nbformat: 4, nbformat_minor: 5,
  metadata: { language_info: { name: "python" } },
  cells: [
    { id: "table", cell_type: "code", metadata: {}, execution_count: 1, source: ["display(region_table)"], outputs: [{ output_type: "display_data", metadata: {}, data: { "text/markdown": "| Region | Tonnes |\n| North | 120 |\n| South | 181 |" } }] },
    { id: "total", cell_type: "code", metadata: {}, execution_count: 2, source: ["total"], outputs: [{ output_type: "execute_result", execution_count: 2, metadata: {}, data: { "text/markdown": "**Total:** 301 tonnes" } }] },
    { id: "control", cell_type: "code", metadata: {}, execution_count: 3, source: ["print('control stream output')"], outputs: [{ output_type: "stream", name: "stdout", text: "control stream output\n" }] },
  ],
});

test("Attached notebook exposes markdown-only saved outputs in its extracted text", WEB, async ({ t3, browser, screen, app }) => {
  const project = await t3.project("notebook-output-proof");
  const thread = await t3.thread({ project, title: "Notebook output extraction", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await browser.evaluate((content) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]');
    if (!input) throw new Error("Attachment file input missing");
    const transfer = new DataTransfer();
    transfer.items.add(new File([content], "tonnage-report.ipynb", { type: "application/x-ipynb+json" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, notebook);
  await screen.getByRole("textbox").fill('Read the extracted text file supplied for the attached notebook (not the .ipynb itself) and quote, verbatim, everything under each cell Output heading.');
  await screen.getByRole("textbox").press("Enter");
  let extracted = "";
  await expect.poll(async () => {
    const files = await fs.readdir(path.join(T3_HOME, "userdata"), { recursive: true });
    const textFile = files.find((file) => file.endsWith(".ipynb.txt"));
    if (!textFile) return false;
    extracted = await fs.readFile(path.join(T3_HOME, "userdata", textFile), "utf8");
    return extracted.includes("control stream output");
  }).toBe(true);
  // Open a byte-for-byte copy through the real app's file viewer, without exposing server paths.
  await fs.writeFile(path.join(project, "tonnage-report.ipynb.txt"), extracted);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("tonnage-report.ipynb.txt");
  await screen.getByRole("option", "tonnage-report.ipynb.txt", { exact: false }).tap();
  await screen.getByText("control stream output", { exact: false }).last().waitFor();
  await app.screenshot("notebook-extracted-output");
  expect(extracted).toContain("| North | 120 |");
  expect(extracted).toContain("| South | 181 |");
  expect(extracted).toContain("**Total:** 301 tonnes");
});
