/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Linux application script MIME attachments display script text", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Script previews");
  const thread = await t3.thread({ project, title: "Review scripts", messages: ["Start"], model: "default" });
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor();
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('[data-chat-composer-form="true"] input[type="file"]');
    if (!input) throw new Error("Composer file input missing");
    const transfer = new DataTransfer();
    for (const [name, type, text] of [
      ["report.pl", "application/x-perl", 'print "hello\\n";\n'],
      ["Util.pm", "application/x-perl", 'package Util;\nsub hello { return "hello"; }\n1;\n'],
      ["fields.awk", "application/x-awk", '{ print $1 }\n'],
      ["setup.csh", "application/x-csh", 'setenv FOO bar\necho $FOO\n'],
      ["build.sh", "application/x-shellscript", 'echo hello\n'],
    ]) transfer.items.add(new File([text], name, { type }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  });
  const results: boolean[] = [];
  for (const [name, content] of [["report.pl", 'print "hello'], ["Util.pm", "package Util;"], ["fields.awk", "print $1"], ["setup.csh", "setenv FOO bar"], ["build.sh", "echo hello"]]) {
    await browser.locator(`[role="button"][aria-label^="File attachment, ${name},"],button[aria-label^="File attachment, ${name},"]`).tap();
    await browser.locator('[role="dialog"]').waitFor();
    const previewText = () => browser.evaluate(() => {
      const dialog = document.querySelector('[role="dialog"]');
      const source = dialog?.querySelector("diffs-container")?.shadowRoot;
      return (dialog?.textContent ?? "") + (source?.textContent ?? "");
    });
    await expect.poll(async () => {
      const text = await previewText();
      return text.includes("No preview for this file") || text.includes(content);
    }, { timeout: 120_000 }).toBe(true);
    await app.screenshot(name);
    results.push((await previewText()).includes(content));
    await browser.keyboard.press("Escape");
  }
  expect(results).toEqual([true, true, true, true, true]);
});
