// SSGI — Screen-Space Global Illumination compute pass manager.
// Approximates indirect diffuse lighting from screen-space data.
// Ping-pong history buffers for temporal accumulation at half resolution.
// Output: Rgba16Float texture sampled in PBR ambient/indirect term.

/// SSGI uniform parameters (matches ssgi.wgsl SsgiParams).
#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct SsgiParams {
    pub inv_proj: [f32; 16],
    pub proj: [f32; 16],
    pub screen_size: [f32; 2],
    pub radius: f32,
    pub intensity: f32,
}

/// SSGI pass: compute indirect illumination from color + depth, accumulate with history.
pub struct SsgiPass {
    compute_pipeline: Option<wgpu::ComputePipeline>,
    bgl: Option<wgpu::BindGroupLayout>,
    params_buf: Option<wgpu::Buffer>,
    gi_texture: Option<wgpu::Texture>,
    gi_view: Option<wgpu::TextureView>,
    gi_history_texture: Option<wgpu::Texture>,
    gi_history_view: Option<wgpu::TextureView>,
    sampler: Option<wgpu::Sampler>,
    /// Which history buffer was last written (false=gi, true=gi_history).
    write_b: bool,
    width: u32,
    height: u32,
    pub enabled: bool,
    initialized: bool,
}

impl Default for SsgiPass {
    fn default() -> Self {
        Self {
            compute_pipeline: None,
            bgl: None,
            params_buf: None,
            gi_texture: None,
            gi_view: None,
            gi_history_texture: None,
            gi_history_view: None,
            sampler: None,
            write_b: false,
            width: 0,
            height: 0,
            enabled: true,
            initialized: false,
        }
    }
}

impl SsgiPass {
    /// Initialize pipeline and allocate ping-pong GI textures at half resolution.
    pub fn init(&mut self, device: &wgpu::Device, width: u32, height: u32) {
        if self.initialized && self.width == width && self.height == height {
            return;
        }

        let half_w = width.max(2) / 2;
        let half_h = height.max(2) / 2;
        let format = wgpu::TextureFormat::Rgba16Float;

        // SSGI bind group layout: params (uniform) + color texture + depth texture + sampler + history texture + storage output
        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ssgi_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::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 5,
                    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("ssgi.wgsl"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/ssgi.wgsl").into()),
        });

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

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

        // GI textures at half resolution (ping-pong)
        let make_gi = |label: &str| -> (wgpu::Texture, wgpu::TextureView) {
            let tex = device.create_texture(&wgpu::TextureDescriptor {
                label: Some(label),
                size: wgpu::Extent3d {
                    width: half_w,
                    height: half_h,
                    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: &[],
            });
            let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
            (tex, view)
        };
        let (gi, giv) = make_gi("ssgi_gi");
        let (gi_hist, gi_histv) = make_gi("ssgi_gi_history");
        self.gi_texture = Some(gi);
        self.gi_view = Some(giv);
        self.gi_history_texture = Some(gi_hist);
        self.gi_history_view = Some(gi_histv);

        if self.sampler.is_none() {
            self.sampler = Some(device.create_sampler(&wgpu::SamplerDescriptor {
                label: Some("ssgi_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("ssgi_params"),
                size: std::mem::size_of::<SsgiParams>() 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!(
            "SSGI initialized ({}x{} → {}x{} GI, ping-pong)",
            width,
            height,
            half_w,
            half_h
        );
    }

    /// Dispatch SSGI compute. Ping-pongs history buffers for temporal accumulation.
    /// Returns the GI texture view for PBR indirect lighting.
    pub fn dispatch(
        &mut 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.compute_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 sampler) = self.sampler else { return None };

        let half_w = self.width.max(2) / 2;
        let half_h = self.height.max(2) / 2;

        // Select read/write GI buffers (ping-pong)
        let (read_view, write_view) = if self.write_b {
            (self.gi_view.as_ref()?, self.gi_history_view.as_ref()?)
        } else {
            (self.gi_history_view.as_ref()?, self.gi_view.as_ref()?)
        };

        // Upload params
        let params = SsgiParams {
            inv_proj: camera.projection_matrix.inverse().to_cols_array(),
            proj: camera.projection_matrix.to_cols_array(),
            screen_size: [self.width as f32, self.height as f32],
            radius: 64.0,
            intensity: 1.5,
        };
        queue.write_buffer(params_buf, 0, bytemuck::bytes_of(&params));

        // SSGI pass: color + depth + history → GI output
        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("ssgi_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(read_view),
                },
                wgpu::BindGroupEntry {
                    binding: 5,
                    resource: wgpu::BindingResource::TextureView(write_view),
                },
            ],
        });
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("ssgi_compute"),
                timestamp_writes: None,
            });
            pass.set_pipeline(pipeline);
            pass.set_bind_group(0, &bg, &[]);
            pass.dispatch_workgroups(half_w.div_ceil(8), half_h.div_ceil(8), 1);
        }

        self.write_b = !self.write_b;

        // Return the just-written buffer as the GI output
        if self.write_b {
            self.gi_history_view.as_ref()
        } else {
            self.gi_view.as_ref()
        }
    }

    /// Get the current GI texture view for external binding.
    pub fn gi_view(&self) -> Option<&wgpu::TextureView> {
        if self.write_b {
            self.gi_history_view.as_ref()
        } else {
            self.gi_view.as_ref()
        }
    }

    pub fn destroy(&mut self) {
        if let Some(t) = self.gi_texture.take() {
            t.destroy();
        }
        if let Some(t) = self.gi_history_texture.take() {
            t.destroy();
        }
        if let Some(b) = self.params_buf.take() {
            b.destroy();
        }
        self.gi_view = None;
        self.gi_history_view = None;
        self.initialized = false;
    }
}

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

    #[test]
    fn ssgi_params_size() {
        assert_eq!(std::mem::size_of::<SsgiParams>(), 144);
    }

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