import fs from 'node:fs';

const input = fs.readFileSync(0, 'utf8').trim();
if (!input) {
  console.error('no foreground color pairs received');
  process.exit(1);
}

const channelLuminance = (value) => {
  const channel = value / 255;
  return channel <= 0.04045
    ? channel / 12.92
    : ((channel + 0.055) / 1.055) ** 2.4;
};

const luminance = (hex) => {
  const channels = hex.match(/../g).map((pair) => Number.parseInt(pair, 16));
  return (
    0.2126 * channelLuminance(channels[0])
    + 0.7152 * channelLuminance(channels[1])
    + 0.0722 * channelLuminance(channels[2])
  );
};

const backgroundLuminance = luminance('E4E4E4');
const failures = [];

for (const line of input.split('\n')) {
  const [dark, light] = line.trim().split(/\s+/);
  if (!/^[0-9A-F]{6}$/.test(dark) || !/^[0-9A-F]{6}$/.test(light)) {
    failures.push(`${line}: expected two six-digit uppercase colors`);
    continue;
  }

  const foregroundLuminance = luminance(light);
  const ratio = (
    Math.max(backgroundLuminance, foregroundLuminance) + 0.05
  ) / (
    Math.min(backgroundLuminance, foregroundLuminance) + 0.05
  );

  if (ratio < 4.5) {
    failures.push(`${dark} -> ${light}: contrast ${ratio.toFixed(2)} is below 4.5`);
  }
}

if (failures.length > 0) {
  console.error(failures.join('\n'));
  process.exit(1);
}
