/// <reference lib="dom" />
import { readFileSync, readdirSync, renameSync } from "node:fs";
import { expect } from "e2e";
import { T3_HOME, APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Copying a failed message preserves its image beside the text", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({project, title:"Image retry", messages:["first"]});
  await browser.addInitScript(() => {
    const pending = Promise.withResolvers<void>();
    (window as any).launchReady = pending.promise;
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string" && JSON.parse(data).tag === "orchestration.launchThread") {
        WebSocket.prototype.send = send;
        (window as any).releaseLaunch = () => send.call(this, data);
        pending.resolve();
        return;
      }
      return send.call(this, data);
    };
  });
  await t3.open(thread);
  await screen.getByRole("button", "New thread in demo", {exact:true}).tap();
  const composer = screen.getByRole("textbox");
  await composer.fill("Describe this image");
  await browser.evaluate(async () => {
    const canvas = new OffscreenCanvas(360, 220);
    const ctx = canvas.getContext("2d")!;
    ctx.fillStyle = "#2266cc"; ctx.fillRect(0,0,360,220);
    ctx.fillStyle = "#ffcc33"; ctx.fillRect(70,45,220,130);
    const files = new DataTransfer();
    files.items.add(new File([await canvas.convertToBlob({type:"image/png"})], "shot.png", {type:"image/png"}));
    const input = document.querySelector('input[type="file"]') as HTMLInputElement;
    input.files = files.files;
    input.dispatchEvent(new Event("change", {bubbles:true}));
  });
  await browser.locator('button[aria-label="Preview shot.png"]:enabled').waitFor();
  await composer.fill("Describe this image");
  const state = JSON.parse(readFileSync(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const cwd = await import("node:fs").then(fs => fs.readlinkSync(`/proc/${state.pid}/cwd`));
  if (!cwd.startsWith(APP_DIR)) throw new Error("Server cwd does not belong to proof checkout");
  await composer.press("Enter");
  await browser.evaluate(() => (window as any).launchReady);
  process.kill(state.pid, "SIGSTOP");
  try {
    await composer.fill("next draft");
    await app.screenshot("pending-send-new-draft");
    const dir = `${T3_HOME}/userdata/attachments`;
    for (const name of readdirSync(dir).filter(name => name.startsWith("pending-"))) renameSync(`${dir}/${name}`, `${dir}/held-${name}`);
    await browser.evaluate(() => { (window as any).releaseLaunch(); });
  } finally { process.kill(state.pid, "SIGCONT"); }
  await screen.getByText("Message not sent", {exact:true}).waitFor();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
  });
  await app.screenshot("failed-send-kept-new-draft");
  await screen.getByRole("button", "Copy message", {exact:true}).tap();
  await composer.tap();
  await composer.press("Control+End");
  await composer.press("Control+v");
  await composer.getByText("Describe this image", {exact:false}).waitFor();
  await app.screenshot("pasted-failed-message");
  await expect(browser.locator('[data-chat-composer-form="true"]').getByRole("button", "Image attachment, shot.png", {exact:false})).toBeVisible();
  await expect(composer).toContainText("Describe this image");
});
