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

test("Reversed ICC segments retain Display P3 through attachment resizing", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Colour preservation");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.refreshProviders"]({ instanceId: ProviderInstanceId.make("devReplay"), fresh: true, refreshModels: true });
  }).pipe(Effect.scoped));
  const thread = await t3.thread({ project, title: "JPEG ICC sequence proof", messages: ["Start"] });
  await t3.open(thread);
  const input = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(input).waitFor({ state: "attached", timeout: 90_000 });
  const source = await browser.evaluate(async (input) => {
    const canvas = new OffscreenCanvas(2400, 1600);
    const ctx = canvas.getContext("2d", { colorSpace: "display-p3" })!;
    ctx.fillStyle = "color(display-p3 0 1 0)";
    ctx.fillRect(0, 0, 1200, 1600);
    ctx.fillStyle = "#888";
    ctx.fillRect(1200, 0, 1200, 1600);
    const bytes = new Uint8Array(await (await canvas.convertToBlob({ type: "image/jpeg", quality: 1 })).arrayBuffer());
    let start = -1, end = -1;
    for (let offset = 2; offset < bytes.length && bytes[offset] === 255;) {
      const size = bytes[offset + 2] * 256 + bytes[offset + 3];
      if (bytes[offset + 1] === 226 && String.fromCharCode(...bytes.slice(offset + 4, offset + 16)) === "ICC_PROFILE\0") {
        start = offset; end = offset + 2 + size; break;
      }
      offset += 2 + size;
    }
    if (start < 0) throw new Error("Chromium did not embed an ICC profile");
    const profile = bytes.slice(start + 18, end);
    const split = Math.ceil(profile.length / 2);
    const segment = (seq: number, data: Uint8Array) => {
      const size = data.length + 16;
      return new Uint8Array([255, 226, size >> 8, size & 255, ...new TextEncoder().encode("ICC_PROFILE\0"), seq, 2, ...data]);
    };
    const one = segment(1, profile.slice(0, split));
    const two = segment(2, profile.slice(split));
    const files = new DataTransfer();
    const samples = [];
    for (const [name, chunks] of [["in-order.jpg", [one, two]], ["reversed.jpg", [two, one]]] as const) {
      const file = new File([bytes.slice(0, start), ...chunks, bytes.slice(end)], name, { type: "image/jpeg" });
      const bitmap = await createImageBitmap(file);
      const sample = new OffscreenCanvas(1, 1).getContext("2d", { colorSpace: "display-p3" })!;
      sample.drawImage(bitmap, 600, 800, 1, 1, 0, 0, 1, 1);
      samples.push({ name, rgba: Array.from(sample.getImageData(0, 0, 1, 1).data) });
      bitmap.close(); files.items.add(file);
    }
    const picker = document.querySelector<HTMLInputElement>(input)!;
    picker.files = files.files;
    picker.dispatchEvent(new Event("change", { bubbles: true }));
    return { profileBytes: profile.length, samples };
  }, input);
  await browser.locator('button[aria-label="Preview reversed.jpg"]:enabled').waitFor();
  await screen.getByRole("textbox").fill("Preserve the green in both JPEGs.");
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  await browser.locator('[data-message-role="user"] button[aria-label="Preview reversed.jpg"]').waitFor();
  await screen.getByRole("button", "Fork from this response").nth(1).waitFor();
  await t3.open(thread);
  await browser.locator('[data-message-role="user"] button[aria-label="Preview reversed.jpg"]').waitFor();
  const results = [];
  for (const name of ["in-order.jpg", "reversed.jpg"]) {
    await browser.locator(`[data-message-role="user"] button[aria-label="Preview ${name}"]`).tap();
    await browser.locator(`img[alt="${name}"]`).last().waitFor();
    const result = await browser.evaluate(async (name) => {
      const images = [...document.querySelectorAll<HTMLImageElement>(`img[alt="${name}"]`)];
      const img = images.at(-1)!;
      await img.decode();
      const blob = await (await fetch(img.currentSrc || img.src)).blob();
      const bitmap = await createImageBitmap(blob);
      const canvas = new OffscreenCanvas(1, 1);
      const ctx = canvas.getContext("2d", { colorSpace: "display-p3" })!;
      ctx.drawImage(bitmap, Math.floor(bitmap.width / 4), Math.floor(bitmap.height / 2), 1, 1, 0, 0, 1, 1);
      const bytes = new Uint8Array(await blob.arrayBuffer());
      const text = new TextDecoder("latin1").decode(bytes).replaceAll("\0", "");
      const result = { name, width: bitmap.width, height: bitmap.height, rgba: Array.from(ctx.getImageData(0, 0, 1, 1).data), profile: text.includes("Display P3") ? "Display P3" : text.includes("sRGB") ? "sRGB" : "unknown", src: img.currentSrc || img.src };
      bitmap.close();
      return result;
    }, name);
    results.push(result);
    await browser.keyboard.press("Escape");
  }
  await browser.evaluate(({ source, results }) => {
    const panel = document.createElement("section");
    panel.style.cssText = "position:fixed;bottom:20px;left:300px;right:24px;z-index:9999;background:#17191f;color:#fff;padding:24px;border:1px solid #777;border-radius:12px;font:16px/1.5 monospace";
    const heading = document.createElement("h2");
    heading.textContent = "Stored attachment colour measurements";
    panel.append(heading);
    const info = document.createElement("p");
    info.textContent = `2400×1600 source • ${source.profileBytes}-byte ICC split into two chunks • Chromium P3 samples: ${source.samples.map(x => x.name + ' ' + x.rgba.join(',')).join(' / ')}`;
    panel.append(info);
    for (const item of results) {
      const row = document.createElement("div");
      row.style.cssText = "display:flex;align-items:center;gap:20px;margin:12px 0";
      const img = document.createElement("img"); img.src = item.src; img.style.cssText = "width:180px;height:120px;object-fit:contain";
      const label = document.createElement("span");
      label.textContent = `${item.name}: ${item.width}×${item.height}\nICC: ${item.profile}\nP3 RGBA: ${item.rgba.join(', ')}`;
      label.style.whiteSpace = "pre-line";
      row.append(img, label); panel.append(row);
    }
    const note = document.createElement("p"); note.textContent = "Diagnostic overlay: decoded uploaded bytes; P3 green should remain ≈ (0,255,1)."; panel.append(note);
    document.body.append(panel);
    return null;
  }, { source, results });
  await app.screenshot("stored-jpeg-colour");
  expect(results.map(({ width, height }) => [width, height])).toEqual([[2000, 1333], [2000, 1333]]);
  expect(results[1].rgba[0]).toBeLessThan(5);
  expect(results[1].rgba[2]).toBeLessThan(5);
});
