/**
 * Cut a region out of a PNG for close inspection, optionally zoomed, or print its pixels.
 *
 *   bun tools/crop.ts <in.png> <x> <y> <w> <h> <out.png> [zoom]   crop (zoom default 1, nearest neighbour)
 *   bun tools/crop.ts <in.png> <x> <y> <w> <h> --hex               print each pixel as #rrggbb[aa]
 */
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'

import { crop, decodePng, encodePng, pixelHex, zoom } from './bench/png'

const [file, xs, ys, ws, hs, out, zs] = process.argv.slice(2)
if (!file || !xs || !ys || !ws || !hs || !out) {
  console.error('usage: bun tools/crop.ts <in.png> <x> <y> <w> <h> (<out.png> [zoom] | --hex)')
  process.exit(2)
}
const [x, y, w, h] = [xs, ys, ws, hs].map(Number) as [number, number, number, number]
const region = crop(decodePng(readFileSync(file)), x, y, w, h)

if (out === '--hex') {
  for (let r = 0; r < h; r++) {
    const row: string[] = []
    for (let c = 0; c < w; c++) row.push(pixelHex(region, c, r))
    console.log(`${String(y + r).padStart(4)}: ${row.join(' ')}`)
  }
} else {
  const factor = zs ? Number(zs) : 1
  mkdirSync(path.dirname(path.resolve(out)), { recursive: true })
  writeFileSync(out, encodePng(factor > 1 ? zoom(region, factor) : region))
  console.log(`[crop] ${out} (${w * factor}x${h * factor})`)
}
