// Sample the middle column of a PNG, top to bottom, so a shot can be read as
// data instead of eyeballed. Usage:
//   node scripts/sample.mjs <png> [x0..1]
import puppeteer from 'puppeteer';
import { pathToFileURL } from 'node:url';
import { resolve } from 'node:path';

const file = resolve(process.argv[2] || 'shot.png');
const fx = Number(process.argv[3] ?? 0.5);
const url = pathToFileURL(file).href;

const browser = await puppeteer.launch({
	headless: true,
	args: ['--allow-file-access-from-files', '--hide-scrollbars'],
});
try {
	const page = await browser.newPage();
	await page.goto(url);
	const rows = await page.evaluate((frac) => {
		const img = document.querySelector('img');
		img.style.imageRendering = 'pixelated';
		const c = document.createElement('canvas');
		c.width = img.naturalWidth;
		c.height = img.naturalHeight;
		const g = c.getContext('2d');
		g.drawImage(img, 0, 0);
		const x = Math.min(img.naturalWidth - 1, Math.round(frac * (img.naturalWidth - 1)));
		const out = [];
		for (let i = 0; i <= 40; i++) {
			const y = Math.min(img.naturalHeight - 1, Math.round((i / 40) * (img.naturalHeight - 1)));
			const d = g.getImageData(x, y, 1, 1).data;
			const hex = [d[0], d[1], d[2]].map((v) => v.toString(16).padStart(2, '0')).join('');
			out.push(`${String(i * 2.5).padStart(5)}%  #${hex}`);
		}
		return out;
	}, fx);
	console.log(`${file} @ x=${fx}`);
	console.log(rows.join('\n'));
} finally {
	await browser.close();
}