use anyhow::{bail, Result};
use clap::Parser;
use image::{DynamicImage, Rgb, RgbImage};

#[derive(Debug, Parser)]
#[command()]
struct Args {
    #[arg(short, long, value_name = "FILE")]
    input: String,
    #[arg(short, long, value_name = "FILE")]
    output: String,
}

fn main() -> Result<()> {
    let args = Args::parse();
    let img = image::open(&args.input)?;
    let img = match img {
        DynamicImage::ImageRgb8(img) => img,
        _ => bail!("Unsupported type: {:?}", img),
    };
    println!("Opened {} ({}x{})", &args.input, img.width(), img.height());
    let mut output = RgbImage::new(128, 128);
    for x in 0..=127 {
        for y in 0..=127 {
            let [r, g, b] = img
                .get_pixel(x * img.width() / 128, y * img.height() / 128)
                .0;
            let luma = r / 4 + g / 2 + b / 4;
            output.put_pixel(
                x,
                y,
                Rgb([
                    (luma as i32 + 64 - x as i32).clamp(0, 255) as u8,
                    luma,
                    (luma as i32 + 64 - y as i32).clamp(0, 255) as u8,
                ]),
            );
        }
    }
    output.save(&args.output)?;
    println!("Wrote {}", &args.output);
    Ok(())
}
