import * as fs from "node:fs/promises";
import { deflateSync } from "node:zlib";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const svg = (color: string, padding = 0) => `<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96"><rect width="96" height="96" fill="${color}"/><!--${"x".repeat(padding)}--></svg>`;
// A real blue PNG with an uncompressed IDAT, so its source exceeds the 4 MiB download limit.
function largePng() {
  const chunk = (type: string, data: Buffer) => {
    const body = Buffer.concat([Buffer.from(type), data]);
    let crc = 0xffffffff;
    for (const byte of body) {
      crc ^= byte;
      for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0);
    }
    const length = Buffer.alloc(4); length.writeUInt32BE(data.length);
    const checksum = Buffer.alloc(4); checksum.writeUInt32BE((crc ^ 0xffffffff) >>> 0);
    return Buffer.concat([length, body, checksum]);
  };
  const size = 1500;
  const header = Buffer.alloc(13);
  header.writeUInt32BE(size, 0); header.writeUInt32BE(size, 4); header[8] = 8; header[9] = 2;
  const pixels = Buffer.alloc((size * 3 + 1) * size);
  for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) pixels[y * (size * 3 + 1) + 1 + x * 3 + 2] = 255;
  return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]), chunk("IHDR", header), chunk("IDAT", deflateSync(pixels, { level: 0 })), chunk("IEND", Buffer.alloc(0))]);
}

test("Oversized replacement icons replace the stale cached project icon", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Icon replacement", { "favicon.svg": svg("red") });
  const thread = await t3.thread({ project, title: "Project icon proof", messages: ["Start"] });
  await t3.open(thread);
  const picker = screen.getByRole("combobox", "Projects", { exact: true });
  const icon = browser.locator('[role="option"] img:not([hidden])').first();
  const cache = () => browser.evaluate(() => new Promise<number>((resolve, reject) => {
    const open = indexedDB.open("t3code:project-favicons", 2);
    open.onerror = () => reject(open.error);
    open.onsuccess = () => {
      const db = open.result;
      const request = db.transaction("images", "readonly").objectStore("images").count();
      request.onsuccess = () => { resolve(request.result); db.close(); };
      request.onerror = () => reject(request.error);
    };
  }));
  const reload = async () => {
    await browser.evaluate(() => { location.reload(); return null; });
    await picker.tap();
    await icon.waitFor({ timeout: 120_000 });
  };
  await picker.tap();
  await icon.waitFor({ timeout: 120_000 });
  await expect.poll(() => icon.getAttribute("src")).toMatch(/^data:image/);
  await expect.poll(cache).toBe(1);
  await app.screenshot("initial-cached-red-icon");
  await fs.writeFile(`${project}/favicon.svg`, svg("green", 46150));
  await reload();
  // Observe both sides through the same settling window, then collect all results before asserting.
  const sample = async (label: string) => {
    const state = await browser.evaluate(async () => {
      const image = document.querySelector('[role="option"] img:not([hidden])') as HTMLImageElement;
      await image.decode();
      const canvas = document.createElement("canvas"); canvas.width = canvas.height = 1;
      const context = canvas.getContext("2d")!; context.drawImage(image, 0, 0, 1, 1);
      return { src: image.src, pixel: Array.from(context.getImageData(0, 0, 1, 1).data) };
    });
    await app.screenshot(label);
    return { ...state, cached: await cache() };
  };
  // Polling here records the persistent bug on base without stopping the remaining reproduction.
  const settle = async () => { try { await expect.poll(() => icon.getAttribute("src")).toMatch(/\/api\/assets\//); } catch {} };
  await settle();
  const green = await sample("oversized-green-svg");
  await reload(); await settle();
  const greenReload = await sample("green-svg-after-second-reload");
  await fs.unlink(`${project}/favicon.svg`);
  await fs.writeFile(`${project}/favicon.png`, largePng());
  await reload(); await settle();
  const blue = await sample("oversized-blue-png");
  await reload(); await settle();
  const blueReload = await sample("blue-png-after-second-reload");
  expect([green, greenReload, blue, blueReload].map(({src, pixel, cached}) => ({ remote: src.includes("/api/assets/"), pixel, cached }))).toEqual([
    { remote: true, pixel: [0,128,0,255], cached: 0 },
    { remote: true, pixel: [0,128,0,255], cached: 0 },
    { remote: true, pixel: [0,0,255,255], cached: 0 },
    { remote: true, pixel: [0,0,255,255], cached: 0 },
  ]);
});
