use image::{GrayImage, Luma};
use std::fs;
use std::path::Path;

use crate::line_assembler::VideoFrame;

// PAL: 1280 samples per line
const WIDTH: u32 = 1280;
const HEIGHT: u32 = 480; // NTSC (576 for PAL)

pub fn save_frames(frames: &[VideoFrame], output_dir: &str, sig_min: f32, sig_max: f32) {
    fs::create_dir_all(output_dir).expect("Could not create output directory");

    let range = (sig_max - sig_min).max(1e-6);
    let mut saved = 0;

    for (i, frame) in frames.iter().enumerate() {
        if frame.lines.is_empty() {
            continue;
        }

        let mut img = GrayImage::new(WIDTH, HEIGHT);

        for y in 0..HEIGHT as usize {
            let line = frame.lines.get(y);

            for x in 0..WIDTH as usize {
                let s = line
                    .and_then(|l| l.samples.get(x))
                    .copied()
                    .unwrap_or(sig_min);

                let luma = ((s - sig_min) / range * 255.0).clamp(0.0, 255.0) as u8;
                img.put_pixel(x as u32, y as u32, Luma([luma]));
            }
        }

        let path = Path::new(output_dir).join(format!("frame_{:04}.png", i));
        img.save(&path).expect("Could not save image");
        saved += 1;
    }

    println!("{saved} image(s) saved to '{output_dir}/'");
}
