import sharp from "sharp";
import { existsSync } from "fs";
import { join } from "path";

const REF = "assets/logos/source/hourglass-mint-25pct.png";
const FULL = process.argv[2];
const OUT = "assets/logos/source/hourglass-mint-full.png";

if (!FULL || !existsSync(FULL)) {
  console.error("Usage: node scripts/match-full-brightness.mjs <draft-full.png>");
  process.exit(1);
}

/** Mean luminance of non-black pixels (0–255). */
async function meanLuma(path) {
  const { data } = await sharp(path).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
  let sum = 0;
  let n = 0;
  for (let i = 0; i < data.length; i += 4) {
    const r = data[i];
    const g = data[i + 1];
    const b = data[i + 2];
    const l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
    if (l > 12) {
      sum += l;
      n++;
    }
  }
  return n ? sum / n : 0;
}

const refLuma = await meanLuma(REF);
let fullLuma = await meanLuma(FULL);
const brightness = Math.min(1, Math.max(0.72, (refLuma / fullLuma) * 0.96));

await sharp(FULL).modulate({ brightness, saturation: 0.92 }).png().toFile(OUT);

fullLuma = await meanLuma(OUT);
console.log(`ref ${refLuma.toFixed(1)} → out ${fullLuma.toFixed(1)} (brightness ${brightness.toFixed(3)})`);
console.log(`wrote ${OUT} — run npm run logos:normalize`);
