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

test("Pasting a copied file restores its reattach marker without reporting rejection", WEB, async ({t3, app, browser, screen}) => {
  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 => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some(provider => provider.instanceId === "devReplay" && provider.models?.some(model => model.slug === "showcase"));
      }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({project, title: "Restore copied attachment", messages: ["Ready"], model: "showcase"});
  await browser.addInitScript(() => {
    Object.assign(window, { copiedAttachment: null });
    navigator.clipboard.write = async ([item]) => {
      const data: Record<string,string> = {};
      for (const type of item.types) data[type] = await (await item.getType(type)).text();
      Object.assign(window, { copiedAttachment: data });
    };
  });
  await t3.open(thread);
  await screen.getByRole("button", "Fork from this response").waitFor();
  const pick = () => browser.evaluate(() => {
    const input = document.querySelector('input[type="file"][multiple]') as HTMLInputElement;
    if (!input) throw new Error("Composer file picker missing");
    const transfer = new DataTransfer();
    transfer.items.add(new File(["Synthetic attachment evidence.\n".repeat(32)], "notes.txt", {type:"text/plain", lastModified: 1234567890000}));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", {bubbles:true}));
  });
  await screen.getByRole("textbox").fill("Please read this file");
  await pick();
  const form = browser.locator('[data-chat-composer-form="true"]');
  await form.getByRole("button", /File attachment, notes.txt/).waitFor();
  await screen.getByRole("button", "Submit message", {exact:true}).tap();
  const sent = browser.locator('[data-message-role="user"]').filter({hasText:"Please read this file"});
  await sent.waitFor();
  await screen.getByRole("button", "Fork from this response").nth(1).waitFor();
  let uploadStarted!: () => void;
  const started = new Promise<void>(resolve => {uploadStarted=resolve;});
  let releaseUpload!: () => void;
  const released = new Promise<void>(resolve => {releaseUpload=resolve;});
  await browser.route(/\/api\/attachments\/upload\//, async (route) => { uploadStarted(); await released; await route.abort().catch(() => {}); });
  await pick();
  await started;
  await t3.open(thread);
  await form.getByText("attach again", {exact:false}).waitFor();
  releaseUpload();
  await app.screenshot("reattach-marker-before-paste");
  await browser.unroute(/\/api\/attachments\/upload\//);
  await sent.hover();
  await sent.getByRole("button", "Copy message").tap();
  await screen.getByRole("textbox").tap();
  await browser.evaluate(async () => {
    const data = (window as unknown as {copiedAttachment:Record<string,string>}).copiedAttachment;
    if (!data?.["web application/x-t3-context-fragment+json"]) throw new Error("Copy did not produce a context fragment");
    const clipboardData = new DataTransfer();
    for (const [type,value] of Object.entries(data)) clipboardData.setData(type,value);
    document.activeElement!.dispatchEvent(new ClipboardEvent("paste", {clipboardData,bubbles:true,cancelable:true}));
  });
  await form.getByText("attach again", {exact:false}).waitFor({state:"hidden"});
  await form.getByRole("button", /File attachment, notes.txt/).first().waitFor();
  await app.screenshot("copied-file-restored");
  const rejectionShown = await browser.evaluate(() => document.body.textContent?.includes("The draft rejected this attachment") ?? false);
  expect(rejectionShown).toBe(false);
  await form.getByRole("button", /File attachment, notes.txt/).first().tap();
  await expect(screen.getByText("Synthetic attachment evidence.", {exact:false}).first()).toBeVisible();
  await app.screenshot("restored-file-opens");
});
