use wgpu::util::DeviceExt;

use crate::RenderTargets;
use crate::camera::Camera2;
use crate::gpu::{Gpu, PICK_FORMAT};
use crate::scene::{SceneRelationGlyph, SketchScene};
use crate::snapshot::{GlyphStyle, Style, decode_png};

pub const ATLAS_SIDE: u32 = 128;
pub const TILE_SIDE: u32 = 32;
pub const GRID_COLS: u32 = 4;
pub const GRID_ROWS: u32 = 4;
pub const GLYPH_COUNT: u32 = 10;

const COMMITTED_ATLAS: &[u8] = include_bytes!("../../assets/relation_glyphs.png");

#[repr(C, align(16))]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct GlyphUniform {
    clip_from_world: [f32; 16],
    glyph_color: [f32; 4],
    pixels_per_mm: f32,
    offset_px: f32,
    tile_px: f32,
    _pad: f32,
}

const UNIFORM_SIZE: u64 = core::mem::size_of::<GlyphUniform>() as u64;

#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct GlyphInstance {
    anchor_mm: [f32; 2],
    offset_dir: [f32; 2],
    pick_id: u32,
    tile_index: u32,
}

const INSTANCE_STRIDE: u64 = core::mem::size_of::<GlyphInstance>() as u64;

pub struct GlyphPipeline {
    device: wgpu::Device,
    queue: wgpu::Queue,
    pipeline: wgpu::RenderPipeline,
    uniform_buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
}

impl GlyphPipeline {
    #[must_use]
    pub fn new(gpu: &Gpu, color_format: wgpu::TextureFormat) -> Self {
        let device = gpu.device().clone();
        let queue = gpu.queue().clone();
        let (atlas_view, sampler) = upload_atlas(&device, &queue);
        let bind_group_layout = create_bind_group_layout(&device);
        let pipeline = create_pipeline(&device, &bind_group_layout, color_format);
        let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("bone-render:glyph-uniform"),
            size: UNIFORM_SIZE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("bone-render:glyph-bg"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: uniform_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(&atlas_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
            ],
        });
        Self {
            device,
            queue,
            pipeline,
            uniform_buffer,
            bind_group,
        }
    }

    pub fn draw(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        targets: RenderTargets<'_>,
        camera: Camera2,
        style: &Style,
        scene: &SketchScene,
    ) {
        let instances: Vec<GlyphInstance> = scene
            .relations()
            .iter()
            .map(|glyph| build_instance(*glyph))
            .collect();
        if instances.is_empty() {
            return;
        }
        let uniform = build_uniform(camera, style.glyphs());
        self.queue
            .write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&uniform));
        let instance_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("bone-render:glyph-instances"),
                contents: bytemuck::cast_slice(&instances),
                usage: wgpu::BufferUsages::VERTEX,
            });
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("bone-render:glyph-pass"),
            color_attachments: &[
                Some(wgpu::RenderPassColorAttachment {
                    view: targets.color,
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: wgpu::StoreOp::Store,
                    },
                }),
                Some(wgpu::RenderPassColorAttachment {
                    view: targets.pick,
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: wgpu::StoreOp::Store,
                    },
                }),
            ],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        pass.set_pipeline(&self.pipeline);
        pass.set_bind_group(0, &self.bind_group, &[]);
        pass.set_vertex_buffer(0, instance_buffer.slice(..));
        let len = instances.len();
        let Ok(count) = u32::try_from(len) else {
            panic!("glyph instance count {len} exceeds u32::MAX");
        };
        pass.draw(0..6, 0..count);
    }
}

impl core::fmt::Debug for GlyphPipeline {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("GlyphPipeline").finish_non_exhaustive()
    }
}

const INSTANCE_ATTRS: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
    0 => Float32x2,
    1 => Float32x2,
    2 => Uint32,
    3 => Uint32,
];

fn create_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("bone-render:glyph-bgl"),
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: wgpu::BufferSize::new(UNIFORM_SIZE),
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: wgpu::ShaderStages::FRAGMENT,
                ty: wgpu::BindingType::Texture {
                    multisampled: false,
                    view_dimension: wgpu::TextureViewDimension::D2,
                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 2,
                visibility: wgpu::ShaderStages::FRAGMENT,
                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                count: None,
            },
        ],
    })
}

fn create_pipeline(
    device: &wgpu::Device,
    bind_group_layout: &wgpu::BindGroupLayout,
    color_format: wgpu::TextureFormat,
) -> wgpu::RenderPipeline {
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("bone-render:glyph-shader"),
        source: wgpu::ShaderSource::Wgsl(include_str!("glyph.wgsl").into()),
    });
    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("bone-render:glyph-layout"),
        bind_group_layouts: &[Some(bind_group_layout)],
        immediate_size: 0,
    });
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("bone-render:glyph-pipeline"),
        layout: Some(&pipeline_layout),
        vertex: wgpu::VertexState {
            module: &shader,
            entry_point: Some("vs"),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            buffers: &[wgpu::VertexBufferLayout {
                array_stride: INSTANCE_STRIDE,
                step_mode: wgpu::VertexStepMode::Instance,
                attributes: &INSTANCE_ATTRS,
            }],
        },
        fragment: Some(wgpu::FragmentState {
            module: &shader,
            entry_point: Some("fs"),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            targets: &[
                Some(wgpu::ColorTargetState {
                    format: color_format,
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                }),
                Some(wgpu::ColorTargetState {
                    format: PICK_FORMAT,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                }),
            ],
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Ccw,
            cull_mode: None,
            polygon_mode: wgpu::PolygonMode::Fill,
            conservative: false,
            unclipped_depth: false,
        },
        depth_stencil: None,
        multisample: wgpu::MultisampleState::default(),
        multiview_mask: None,
        cache: None,
    })
}

#[allow(
    clippy::cast_possible_truncation,
    reason = "mm coordinates fit f32 mantissa at CAD scales"
)]
fn build_instance(glyph: SceneRelationGlyph) -> GlyphInstance {
    let (ax, ay) = glyph.anchor_mm().coords_mm();
    let (dx, dy) = glyph.offset_dir().coords_mm();
    GlyphInstance {
        anchor_mm: [ax as f32, ay as f32],
        offset_dir: [dx as f32, dy as f32],
        pick_id: glyph.pick().raw(),
        tile_index: glyph.kind().tile_index(),
    }
}

#[allow(
    clippy::cast_possible_truncation,
    reason = "mm coordinates fit f32 mantissa at CAD scales"
)]
fn build_uniform(camera: Camera2, glyphs: GlyphStyle) -> GlyphUniform {
    GlyphUniform {
        clip_from_world: camera.clip_from_world_mm(),
        glyph_color: glyphs.color().to_rgba_array(),
        pixels_per_mm: camera.zoom().value() as f32,
        offset_px: glyphs.offset_px(),
        tile_px: glyphs.tile_px(),
        _pad: 0.0,
    }
}

fn upload_atlas(device: &wgpu::Device, queue: &wgpu::Queue) -> (wgpu::TextureView, wgpu::Sampler) {
    let Ok((extent, rgba)) = decode_png(COMMITTED_ATLAS) else {
        panic!("committed relation_glyphs.png failed to decode; repo state is broken");
    };
    assert_eq!(
        (extent.width().value(), extent.height().value()),
        (ATLAS_SIDE, ATLAS_SIDE),
        "committed relation_glyphs.png extent must equal ATLAS_SIDE on every side",
    );
    assert_eq!(
        rgba.len(),
        (ATLAS_SIDE * ATLAS_SIDE * 4) as usize,
        "committed relation_glyphs.png rgba length mismatch",
    );
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("bone-render:glyph-atlas"),
        size: wgpu::Extent3d {
            width: ATLAS_SIDE,
            height: ATLAS_SIDE,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba8Unorm,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        &rgba,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(ATLAS_SIDE * 4),
            rows_per_image: Some(ATLAS_SIDE),
        },
        wgpu::Extent3d {
            width: ATLAS_SIDE,
            height: ATLAS_SIDE,
            depth_or_array_layers: 1,
        },
    );
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
        label: Some("bone-render:glyph-sampler"),
        address_mode_u: wgpu::AddressMode::ClampToEdge,
        address_mode_v: wgpu::AddressMode::ClampToEdge,
        address_mode_w: wgpu::AddressMode::ClampToEdge,
        mag_filter: wgpu::FilterMode::Linear,
        min_filter: wgpu::FilterMode::Linear,
        mipmap_filter: wgpu::MipmapFilterMode::Nearest,
        ..Default::default()
    });
    (view, sampler)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scene::RelationGlyphKind;
    use crate::snapshot::{SnapshotFrame, encode_png};
    use crate::{BackendTag, ViewportExtent, ViewportPx};

    const UPDATE_ENV: &str = "BONE_UPDATE_GLYPH_ATLAS";

    #[must_use]
    fn build_atlas_rgba() -> Vec<u8> {
        (0..ATLAS_SIDE)
            .flat_map(|y| (0..ATLAS_SIDE).flat_map(move |x| pixel_rgba(x, y)))
            .collect()
    }

    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_precision_loss,
        clippy::cast_sign_loss,
        reason = "atlas tile coords fit f32 mantissa and coverage is clamped to [0, 1] before u8 scaling"
    )]
    fn pixel_rgba(x: u32, y: u32) -> [u8; 4] {
        let col = x / TILE_SIDE;
        let row = y / TILE_SIDE;
        let local_x = (x % TILE_SIDE) as f32 + 0.5;
        let local_y = (y % TILE_SIDE) as f32 + 0.5;
        let kind = row * GRID_COLS + col;
        let coverage = sample_tile(kind, local_x, local_y);
        let alpha = (coverage.clamp(0.0, 1.0) * 255.0).round() as u8;
        [255, 255, 255, alpha]
    }

    fn sample_tile(kind: u32, x: f32, y: f32) -> f32 {
        RelationGlyphKind::from_index(kind).map_or(0.0, |k| tile_coverage(k, x, y))
    }

    fn tile_coverage(kind: RelationGlyphKind, x: f32, y: f32) -> f32 {
        match kind {
            RelationGlyphKind::Coincident => disc(x, y, 16.0, 16.0, 4.5),
            RelationGlyphKind::Horizontal => segment(x, y, 6.0, 16.0, 26.0, 16.0, 1.8),
            RelationGlyphKind::Vertical => segment(x, y, 16.0, 6.0, 16.0, 26.0, 1.8),
            RelationGlyphKind::Parallel => combine(
                segment(x, y, 10.0, 24.0, 18.0, 8.0, 1.8),
                segment(x, y, 16.0, 24.0, 24.0, 8.0, 1.8),
            ),
            RelationGlyphKind::Perpendicular => combine(
                segment(x, y, 11.0, 6.0, 11.0, 24.0, 1.8),
                segment(x, y, 8.0, 24.0, 24.0, 24.0, 1.8),
            ),
            RelationGlyphKind::Tangent => combine(
                ring(x, y, 16.0, 15.0, 7.0, 1.8),
                segment(x, y, 5.0, 22.0, 27.0, 22.0, 1.8),
            ),
            RelationGlyphKind::Equal => combine(
                segment(x, y, 7.0, 13.0, 25.0, 13.0, 1.8),
                segment(x, y, 7.0, 19.0, 25.0, 19.0, 1.8),
            ),
            RelationGlyphKind::Concentric => combine(
                ring(x, y, 16.0, 16.0, 10.0, 1.8),
                ring(x, y, 16.0, 16.0, 4.0, 1.8),
            ),
            RelationGlyphKind::Fix => fix_anchor(x, y),
            RelationGlyphKind::Midpoint => combine(
                segment(x, y, 6.0, 16.0, 26.0, 16.0, 1.8),
                segment(x, y, 16.0, 11.0, 16.0, 21.0, 1.8),
            ),
            RelationGlyphKind::Symmetric => combine(
                segment(x, y, 16.0, 4.0, 16.0, 28.0, 1.4),
                combine(disc(x, y, 9.0, 16.0, 3.5), disc(x, y, 23.0, 16.0, 3.5)),
            ),
        }
    }

    fn disc(x: f32, y: f32, cx: f32, cy: f32, radius: f32) -> f32 {
        let dx = x - cx;
        let dy = y - cy;
        aa((dx * dx + dy * dy).sqrt() - radius)
    }

    fn ring(x: f32, y: f32, cx: f32, cy: f32, radius: f32, half_thickness: f32) -> f32 {
        let dx = x - cx;
        let dy = y - cy;
        let d = (dx * dx + dy * dy).sqrt();
        aa((d - radius).abs() - half_thickness)
    }

    fn segment(x: f32, y: f32, x0: f32, y0: f32, x1: f32, y1: f32, half_thickness: f32) -> f32 {
        let dx = x1 - x0;
        let dy = y1 - y0;
        let len2 = dx * dx + dy * dy;
        let t = if len2 > 0.0 {
            (((x - x0) * dx + (y - y0) * dy) / len2).clamp(0.0, 1.0)
        } else {
            0.0
        };
        let px = x0 + t * dx;
        let py = y0 + t * dy;
        let ex = x - px;
        let ey = y - py;
        aa((ex * ex + ey * ey).sqrt() - half_thickness)
    }

    fn fix_anchor(x: f32, y: f32) -> f32 {
        let dx = (x - 16.0).abs();
        let dy = (y - 16.0).abs();
        let outer = aa(dx.max(dy) - 7.5);
        let inner = aa(4.0 - dx.max(dy));
        (outer - inner).clamp(0.0, 1.0)
    }

    fn combine(a: f32, b: f32) -> f32 {
        a.max(b)
    }

    fn aa(signed_distance: f32) -> f32 {
        (0.5 - signed_distance).clamp(0.0, 1.0)
    }

    fn atlas_extent() -> ViewportExtent {
        ViewportExtent::square(ViewportPx::new(ATLAS_SIDE))
    }

    fn tag() -> BackendTag {
        BackendTag::from_backend(wgpu::Backend::Noop)
    }

    fn atlas_frame() -> SnapshotFrame {
        SnapshotFrame::new(atlas_extent(), build_atlas_rgba(), tag())
    }

    #[test]
    fn committed_atlas_matches_generator() {
        let Ok(generated_png) = encode_png(&atlas_frame()) else {
            panic!("encode_png on generated atlas failed");
        };
        if std::env::var(UPDATE_ENV).is_ok() {
            let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("assets/relation_glyphs.png");
            if let Some(parent) = path.parent()
                && let Err(e) = std::fs::create_dir_all(parent)
            {
                panic!("create assets dir {}: {e}", parent.display());
            }
            if let Err(e) = std::fs::write(&path, &generated_png) {
                panic!("write atlas {}: {e}", path.display());
            }
            return;
        }
        assert_eq!(
            COMMITTED_ATLAS, generated_png,
            "committed relation_glyphs.png drifted from build_atlas_rgba; \
             rerun with {UPDATE_ENV}=1 to refresh",
        );
    }

    const _: () = assert!(GLYPH_COUNT <= GRID_COLS * GRID_ROWS);

    #[test]
    fn atlas_extent_matches_grid() {
        let rgba = build_atlas_rgba();
        assert_eq!(rgba.len(), (ATLAS_SIDE * ATLAS_SIDE * 4) as usize);
        assert_eq!(ATLAS_SIDE, TILE_SIDE * GRID_COLS);
        assert_eq!(ATLAS_SIDE, TILE_SIDE * GRID_ROWS);
    }

    #[test]
    fn every_tile_has_visible_coverage() {
        let rgba = build_atlas_rgba();
        let empty: Vec<RelationGlyphKind> = RelationGlyphKind::all()
            .into_iter()
            .filter(|kind| tile_alpha_sum(&rgba, *kind) == 0)
            .collect();
        assert!(
            empty.is_empty(),
            "tiles rasterised empty: {empty:?} — coverage fn regressed",
        );
    }

    fn tile_alpha_sum(rgba: &[u8], kind: RelationGlyphKind) -> u32 {
        let idx = kind.tile_index();
        let col = idx % GRID_COLS;
        let row = idx / GRID_COLS;
        let x0 = col * TILE_SIDE;
        let y0 = row * TILE_SIDE;
        (0..TILE_SIDE)
            .flat_map(|dy| (0..TILE_SIDE).map(move |dx| (dx, dy)))
            .map(|(dx, dy)| {
                let x = x0 + dx;
                let y = y0 + dy;
                let base = ((y * ATLAS_SIDE + x) * 4 + 3) as usize;
                u32::from(rgba[base])
            })
            .sum()
    }
}
