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

test("Inherited-property extensions attach as plain files", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Attachment demo", {
    "photo.png": new Uint8Array(Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAeklEQVR4nO3PUQkAIBTAwJfCxua1giH8OITBAtxm7fN1wwUNaEEDWtCAFjSgBQ1oQQNa0IAWNKAFDWhBA1rQgBY0oAUNaEEDWtCAFjSgBQ1oQQNa0IAWNKAFDWhBA1rQgBY0oAUNaEEDWtCAFjSgBQ1oQQNa0IAWPHYBcKehaRTvbBQAAAAASUVORK5CYII=", "base64")),
    "notes.txt": "plain text notes",
    "notes.constructor": "plain text notes",
    "notes.__proto__": "plain text notes",
  });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter(event => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some(p => p.instanceId === "devReplay" && p.models?.some(m => m.slug === "multi-turn"));
      }), Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  await t3.thread({ project, title: "File attachments", messages: ["first"] });
  await t3.open();
  await screen.getByRole("textbox").waitFor();
  await screen.getByRole("textbox").fill("Review these plain text notes and the blue image control.");
  await browser.evaluate(() => {
    document.addEventListener("change", (event) => {
      if (!(event.target instanceof HTMLInputElement) || event.target.type !== "file") return;
      const files = Array.from(event.target.files ?? []);
      document.documentElement.dataset.pickedTypes = JSON.stringify(files.map(f => ({name: f.name, type: f.type, size: f.size})));
    }, true);
    return null;
  });
  await screen.getByRole("button", "Attach files", { exact: true }).setInputFiles([
    `${project}/notes.txt`, `${project}/notes.constructor`, `${project}/notes.__proto__`, `${project}/photo.png`,
  ]);
  console.log("Picker MIME types:", await browser.evaluate(() => document.documentElement.dataset.pickedTypes));
  await screen.getByRole("button", "File attachment, notes.txt, 1 KB", { exact: true }).waitFor();
  await browser.locator('button[aria-label="Preview photo.png"]:enabled').waitFor();
  await app.screenshot("picker-plain-files-and-image-control");
  await browser.evaluate(() => {
    const transfer = new DataTransfer();
    for (const name of ["generic.constructor", "generic.__proto__"]) {
      transfer.items.add(new File(["plain text notes"], name, { type: "application/octet-stream" }));
    }
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new DragEvent("drop", { dataTransfer: transfer, bubbles: true, cancelable: true }));
    return null;
  });
  await browser.locator('[aria-label*="attachment, generic.__proto__,"]').waitFor();
  await app.screenshot("generic-mime-drop");
  await expect(screen.getByRole("button", "File attachment, notes.constructor, 1 KB", { exact: true })).toBeVisible();
  await expect(screen.getByRole("button", "File attachment, notes.__proto__, 1 KB", { exact: true })).toBeVisible();
  await expect(screen.getByRole("button", "File attachment, generic.constructor, 1 KB", { exact: true })).toBeVisible();
  await expect(screen.getByRole("button", "File attachment, generic.__proto__, 1 KB", { exact: true })).toBeVisible();
});
