use wgpu::{Device, Queue, Texture, TextureDescriptor, TextureUsages, Extent3d};
use image::DynamicImage;
use crate::runtime::AssetResult;

/// DynamicImage를 GPU 텍스처로 변환
pub fn create_texture_from_image(
    device: &Device,
    queue: &Queue,
    image: &DynamicImage,
) -> AssetResult<Texture> {
    let rgba = image.to_rgba8();
    let dimensions = rgba.dimensions();
    
    let size = Extent3d {
        width: dimensions.0,
        height: dimensions.1,
        depth_or_array_layers: 1,
    };
    
    let texture = device.create_texture(&TextureDescriptor {
        label: Some("Loaded Texture"),
        size,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba8UnormSrgb,
        usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
        view_formats: &[],
    });
    
    queue.write_texture(
        texture.as_image_copy(),
        &rgba,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(4 * dimensions.0),
            rows_per_image: Some(dimensions.1),
        },
        size,
    );
    
    Ok(texture)
}

pub fn create_placeholder_texture(
    device: &Device,
    queue: &Queue,
    color: [u8; 4],
) -> Texture {
    let size = Extent3d {
        width: 1,
        height: 1,
        depth_or_array_layers: 1,
    };
    
    let texture = device.create_texture(&TextureDescriptor {
        label: Some("Placeholder Texture"),
        size,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba8UnormSrgb,
        usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
        view_formats: &[],
    });
    
    queue.write_texture(
        texture.as_image_copy(),
        &color,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(4),
            rows_per_image: Some(1),
        },
        size,
    );
    
    texture
}