import { readFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const original = readFileSync(new URL("../../apps/web/test/fixtures/images/photo.heic", import.meta.url));
const padding = 1_048_576;
for (const offset of [464, 478]) original.writeUInt32BE(original.readUInt32BE(offset) + padding, offset);
const free = Buffer.alloc(padding);
free.writeUInt32BE(padding, 0);
free.write("free", 4);
const payload = Buffer.concat([original.subarray(0, 36), free, original.subarray(36)]).toString("base64");

test("HEIC metadata after a large free box stages as JPEG", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("HEIC photos");
  const seed = () => t3.thread({project, title: "Attach padded HEIC photo", messages: ["first"], model: "multi-turn"});
  const thread = await seed().catch((error: unknown) => {
    if (!String(error).includes("Advertised models: default.")) throw error;
    return seed();
  });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Inspect this HEIC photo ");
  await browser.evaluate((base64: string) => {
    const editor = document.querySelector('[contenteditable="true"]');
    if (!editor) throw new Error("Composer missing");
    const transfer = new DataTransfer();
    transfer.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], "photo.heic", {type: "image/heif"}));
    editor.dispatchEvent(new DragEvent("drop", {dataTransfer: transfer, bubbles: true, cancelable: true}));
    return new Promise<void>((resolve) => {
      const done = () => {
        if (document.body.textContent?.includes("could not be read as an image") || document.querySelector('[aria-label*="Image attachment, photo.jpg"]')) {observer.disconnect(); resolve();}
      };
      const observer = new MutationObserver(done);
      observer.observe(document.body, {childList: true, subtree: true, attributes: true});
      done();
    });
  }, payload);
  await app.screenshot("padded-heic-attachment");
  await expect(screen.getByRole("button", "Image attachment, photo.jpg", {exact: false})).toBeVisible();
});
