/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";

declare global { interface Window { copiedMessage: Promise<ClipboardItem>; } }

test("A copied file cannot take a preparing screenshot's final attachment slot", WEB, async ({ t3, app, browser, screen }) => {
  await browser.addInitScript(() => {
    const copied = Promise.withResolvers<ClipboardItem>();
    navigator.clipboard.write = async ([item]) => { if (item) copied.resolve(item); };
    window.copiedMessage = copied.promise;
  });
  const project = await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter((event) => (event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : []).some((provider) => provider.instanceId === "devReplay" && provider.models?.some((model) => model.slug === "multi-turn"))), Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({ project, title: "Attachment slot race", messages: ["first"] });
  await t3.open(thread);
  await browser.locator('[data-message-role="user"]').filter({ hasText: "first" }).waitFor();
  const editor = screen.getByRole("textbox");
  const form = browser.locator('[data-chat-composer-form="true"]');
  await browser.locator('[data-chat-composer-form] input[type="file"]').waitFor({ state: "attached" });
  await editor.fill("Here are my notes");
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('[data-chat-composer-form] input[type="file"]')!;
    const data = new DataTransfer();
    data.items.add(new File(["Synthetic notes\n".repeat(64)], "notes.txt", { type: "text/plain" }));
    input.files = data.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  });
  await form.getByRole("button", "File attachment, notes.txt", { exact: false }).waitFor();
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  await screen.getByRole("button", "Fork from this response").nth(1).waitFor();
  const sent = browser.locator('[data-message-role="user"]').filter({ hasText: "Here are my notes" });
  await sent.hover();
  await sent.getByRole("button", "Copy message").tap();
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('[data-chat-composer-form] input[type="file"]')!;
    const data = new DataTransfer();
    for (let i = 0; i < 99; i++) data.items.add(new File([`Synthetic file ${i}`], `file-${i}.txt`, { type: "text/plain" }));
    input.files = data.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  });
  await form.getByRole("button", "File attachment, file-98.txt", { exact: false }).waitFor();
  await form.getByText(/^\d+%$/).first().waitFor({ state: "hidden" });
  await browser.mouse.move(280, 400);
  await browser.evaluate(() => {
    const editor = document.querySelector<HTMLElement>('[contenteditable="true"]')!;
    editor.focus();
    const range = document.createRange(); range.selectNodeContents(editor); range.collapse(false);
    const selection = window.getSelection()!; selection.removeAllRanges(); selection.addRange(range);
    return null;
  });
  // A real ~40 MB noisy PNG takes long enough to paste the copied message during preparation.
  await browser.evaluate(async () => {
    const canvas = new OffscreenCanvas(3700, 3700);
    const ctx = canvas.getContext("2d")!;
    const pixels = ctx.createImageData(3700, 3700);
    let n = 123456789;
    for (let i = 0; i < pixels.data.length; i += 4) {
      n ^= n << 13; n ^= n >>> 17; n ^= n << 5;
      pixels.data[i] = n & 255; pixels.data[i + 1] = (n >>> 8) & 255; pixels.data[i + 2] = (n >>> 16) & 255; pixels.data[i + 3] = 255;
    }
    ctx.putImageData(pixels, 0, 0);
    const data = new DataTransfer();
    data.items.add(new File([await canvas.convertToBlob({ type: "image/png" })], "screenshot.png", { type: "image/png" }));
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }));
    return null;
  });
  await form.getByText("Preparing", { exact: true }).waitFor();
  await app.screenshot("screenshot-reserves-final-slot");
  await browser.evaluate(async () => {
    const copied = await window.copiedMessage as ClipboardItem;
    const data = new DataTransfer();
    for (const type of copied.types) data.setData(type, await (await copied.getType(type)).text());
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }));
    return null;
  });
  // Wait for the real copied-file import to either succeed or show its limit error.
  await browser.locator('[data-chat-composer-form] [aria-label^="File attachment, notes.txt"], [data-slot="toast-title"]').first().waitFor();
  await browser.evaluate(() => {
    const editor = document.querySelector<HTMLElement>('[contenteditable="true"]')!;
    editor.scrollTop = editor.scrollHeight;
    return null;
  });
  await app.screenshot("copied-file-during-preparation");
  await form.getByText("Preparing", { exact: true }).waitFor({ state: "hidden" });
  await browser.evaluate(() => {
    const editor = document.querySelector<HTMLElement>('[contenteditable="true"]')!;
    editor.scrollTop = editor.scrollHeight;
    return null;
  });
  await app.screenshot("final-attachment-slot");
  await expect(form.getByRole("button", "Preview screenshot.webp", { exact: true })).toBeVisible();
  await expect(screen.getByText("Couldn't bring notes.txt into this message", { exact: false })).toBeVisible();
});
