import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, IOS } from "./t3-mobile.ts";

function orangePixels(path: string): number {
  const histogram = execFileSync("convert", [path, "-format", "%c", "histogram:info:"], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
  return histogram.split("\n").reduce((count, line) => {
    const match = /^\s*(\d+):\s*\((\d+),(\d+),(\d+)/.exec(line);
    if (!match) return count;
    const [, n, r, g, b] = match.map(Number);
    return count + (r > 180 && g > 20 && g < 110 && b < 45 ? n : 0);
  }, 0);
}

test("iOS Azure author and reviewer images load without Azure cookies", IOS, async ({ t3, app, screen }) => {
  const project = await t3.project("Avatar proof");
  if (!process.env.AVATAR_PROOF_REMOTE) throw new Error("AVATAR_PROOF_REMOTE is required");
  execFileSync("git", ["remote", "add", "origin", process.env.AVATAR_PROOF_REMOTE], { cwd: project });
  await t3.thread({ project, title: "Avatar investigation", messages: ["Show the profile picture fixture"] });
  await t3.open();
  await screen.getByRole("tab", "PRs", { exact: true }).tap();
  await screen.getByText(/Pull request 11, Profile picture proof/).waitFor({ state: "visible" });
  await screen.getByText(/Pull request 11, Profile picture proof/).tap();
  await screen.getByText("Synthetic evidence fixture: author and reviewer avatars.", { exact: true }).waitFor({ state: "visible" });
  await screen.getByRole("button", /Awaiting review/).tap();
  await screen.getByRole("image", /@/).nth(1).waitFor({ state: "visible" });
  const detail = await app.screenshot("ios-author-and-reviewer");
  await screen.getByRole("button", "Back", { exact: true }).tap();
  await screen.getByText(/Pull request 11, Profile picture proof/).waitFor({ state: "visible" });
  const list = await app.screenshot("ios-author-list");
  expect(orangePixels(list)).toBeGreaterThan(100);
  expect(orangePixels(detail)).toBeGreaterThan(100);
});
