// DOF — Depth of Field compute pass manager.
// Applies variable-radius blur based on distance from focal plane.
// Output: Rgba16Float texture with bokeh-style defocus.

/// DOF uniform parameters (matches dof.wgsl DofParams).
#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct DofParams {
    pub focal_distance: f32,
    pub focal_range: f32,
    pub aperture: f32,
    pub max_blur: f32,
    pub screen_size: [f32; 2],
    pub near_plane: f32,
    pub far_plane: f32,
}

/// DOF pass: compute depth-dependent blur from HDR + depth, output defocused texture.
pub struct DofPass {
    pipeline: Option<wgpu::ComputePipeline>,
    bgl: Option<wgpu::BindGroupLayout>,
    params_buf: Option<wgpu::Buffer>,
    output_texture: Option<wgpu::Texture>,
    output_view: Option<wgpu::TextureView>,
    sampler: Option<wgpu::Sampler>,
    width: u32,
    height: u32,
    pub enabled: bool,
    initialized: bool,
}

impl Default for DofPass {
    fn default() -> Self {
        Self {
            pipeline: None,
            bgl: None,
            params_buf: None,
            output_texture: None,
            output_view: None,
            sampler: None,
            width: 0,
            height: 0,
            enabled: false,
            initialized: false,
        }
    }
}

impl DofPass {
    /// Initialize pipeline and allocate output texture for the given resolution.
    pub fn init(&mut self, device: &wgpu::Device, width: u32, height: u32) {
        if self.initialized && self.width == width && self.height == height {
            return;
        }

        let format = wgpu::TextureFormat::Rgba16Float;

        // DOF bind group layout: params (uniform) + color texture + depth texture + sampler + storage output
        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("dof_bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Depth,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 4,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::StorageTexture {
                        access: wgpu::StorageTextureAccess::WriteOnly,
                        format,
                        view_dimension: wgpu::TextureViewDimension::D2,
                    },
                    count: None,
                },
            ],
        });

        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("dof.wgsl"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/dof.wgsl").into()),
        });

        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("dof_layout"),
            bind_group_layouts: &[Some(&bgl)],
            immediate_size: 0,
        });

        self.pipeline = Some(device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("dof_compute"),
            layout: Some(&layout),
            module: &shader,
            entry_point: Some("main"),
            compilation_options: Default::default(),
            cache: None,
        }));

        // Output texture at full resolution
        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("dof_output"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        self.output_view = Some(tex.create_view(&wgpu::TextureViewDescriptor::default()));
        self.output_texture = Some(tex);

        if self.sampler.is_none() {
            self.sampler = Some(device.create_sampler(&wgpu::SamplerDescriptor {
                label: Some("dof_sampler"),
                mag_filter: wgpu::FilterMode::Linear,
                min_filter: wgpu::FilterMode::Linear,
                ..Default::default()
            }));
        }

        if self.params_buf.is_none() {
            self.params_buf = Some(device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("dof_params"),
                size: std::mem::size_of::<DofParams>() as u64,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            }));
        }

        self.bgl = Some(bgl);
        self.width = width;
        self.height = height;
        self.initialized = true;

        log::info!("DOF initialized ({}x{} output)", width, height);
    }

    /// Dispatch DOF compute. Returns the defocused output texture view.
    pub fn dispatch(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        hdr_view: &wgpu::TextureView,
        depth_view: &wgpu::TextureView,
        camera: &crate::camera::Camera,
    ) -> Option<&wgpu::TextureView> {
        if !self.enabled || !self.initialized {
            return None;
        }
        let Some(ref pipeline) = self.pipeline else { return None };
        let Some(ref bgl) = self.bgl else { return None };
        let Some(ref params_buf) = self.params_buf else {
            return None;
        };
        let Some(ref output_view) = self.output_view else {
            return None;
        };
        let Some(ref sampler) = self.sampler else { return None };

        // Upload params
        let params = DofParams {
            focal_distance: 10.0,
            focal_range: 5.0,
            aperture: 0.5,
            max_blur: 8.0,
            screen_size: [self.width as f32, self.height as f32],
            near_plane: camera.near_far.x,
            far_plane: camera.near_far.y,
        };
        queue.write_buffer(params_buf, 0, bytemuck::bytes_of(&params));

        // DOF pass: color + depth → defocused output
        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("dof_bg"),
            layout: bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: params_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(hdr_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(depth_view),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::Sampler(sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: wgpu::BindingResource::TextureView(output_view),
                },
            ],
        });
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("dof_compute"),
                timestamp_writes: None,
            });
            pass.set_pipeline(pipeline);
            pass.set_bind_group(0, &bg, &[]);
            pass.dispatch_workgroups(self.width.div_ceil(8), self.height.div_ceil(8), 1);
        }

        Some(output_view)
    }

    pub fn destroy(&mut self) {
        if let Some(t) = self.output_texture.take() {
            t.destroy();
        }
        if let Some(b) = self.params_buf.take() {
            b.destroy();
        }
        self.output_view = None;
        self.initialized = false;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dof_params_size() {
        assert_eq!(std::mem::size_of::<DofParams>(), 32);
    }

    #[test]
    fn dof_default_disabled() {
        let pass = DofPass::default();
        assert!(!pass.enabled);
        assert!(!pass.initialized);
    }
}
