// Target-agnostic WebGPU types, enums, usage bitflags, and WGSL word helpers.
//
// Shared by both `laplaceliu/tycho_webgpu/native` (webgpu.h C ABI) and
// `laplaceliu/tycho_webgpu/js` (browser `navigator.gpu`).

///|
/// Errors reported by the WebGPU binding layer.
pub(all) suberror WgpuError {
  InitFailed(String)
  DeviceFailed(String)
  ShaderFailed(String)
  PipelineFailed(String)
  TextureFailed(String)
  BufferFailed(String)
  CommandFailed(String)
  ReadbackFailed(String)
  InvalidArgument(String)
}

///|
pub impl Show for WgpuError with output(self, logger) {
  match self {
    InitFailed(msg) => logger.write_string("InitFailed(\{msg})")
    DeviceFailed(msg) => logger.write_string("DeviceFailed(\{msg})")
    ShaderFailed(msg) => logger.write_string("ShaderFailed(\{msg})")
    PipelineFailed(msg) => logger.write_string("PipelineFailed(\{msg})")
    TextureFailed(msg) => logger.write_string("TextureFailed(\{msg})")
    BufferFailed(msg) => logger.write_string("BufferFailed(\{msg})")
    CommandFailed(msg) => logger.write_string("CommandFailed(\{msg})")
    ReadbackFailed(msg) => logger.write_string("ReadbackFailed(\{msg})")
    InvalidArgument(msg) => logger.write_string("InvalidArgument(\{msg})")
  }
}

///|
/// `TextureFormat` ordinals. The integer `code()` values match the encoding
/// `wgpu_stub.c` maps to `WGPUTextureFormat`; `wgpu_name()` yields the exact
/// WebGPU string token used by browser `navigator.gpu`.
#derive(Eq, Debug)
pub(all) enum TextureFormat {
  RGBA8
  BGRA8
  RGBA8Srgb
  BGRA8Srgb
  RGBA16F
  RG16F
  R8
  RGBA32F
  Depth32F
  Depth24Stencil8
}

///|
pub fn TextureFormat::code(self : TextureFormat) -> Int {
  match self {
    RGBA8 => 0
    BGRA8 => 1
    RGBA8Srgb => 2
    BGRA8Srgb => 3
    RGBA16F => 4
    RG16F => 5
    R8 => 6
    RGBA32F => 7
    Depth32F => 8
    Depth24Stencil8 => 9
  }
}

///|
pub fn TextureFormat::from_code(code : Int) -> TextureFormat {
  match code {
    1 => BGRA8
    2 => RGBA8Srgb
    3 => BGRA8Srgb
    4 => RGBA16F
    5 => RG16F
    6 => R8
    7 => RGBA32F
    8 => Depth32F
    9 => Depth24Stencil8
    _ => RGBA8
  }
}

///|
pub fn TextureFormat::wgpu_name(self : TextureFormat) -> String {
  match self {
    RGBA8 => "rgba8unorm"
    BGRA8 => "bgra8unorm"
    RGBA8Srgb => "rgba8unorm-srgb"
    BGRA8Srgb => "bgra8unorm-srgb"
    RGBA16F => "rgba16float"
    RG16F => "rg16float"
    R8 => "r8unorm"
    RGBA32F => "rgba32float"
    Depth32F => "depth32float"
    Depth24Stencil8 => "depth24plus-stencil8"
  }
}

///|
pub fn TextureFormat::from_wgpu_name(name : String) -> TextureFormat {
  match name {
    "bgra8unorm" => BGRA8
    "rgba8unorm-srgb" => RGBA8Srgb
    "bgra8unorm-srgb" => BGRA8Srgb
    "rgba16float" => RGBA16F
    "rg16float" => RG16F
    "r8unorm" => R8
    "rgba32float" => RGBA32F
    "depth32float" => Depth32F
    "depth24plus-stencil8" => Depth24Stencil8
    _ => RGBA8
  }
}

///|
pub fn TextureFormat::is_depth(self : TextureFormat) -> Bool {
  match self {
    Depth32F | Depth24Stencil8 => true
    _ => false
  }
}

///|
pub fn TextureFormat::texel_bytes(self : TextureFormat) -> Int {
  match self {
    R8 => 1
    RGBA16F => 8
    RGBA32F => 16
    _ => 4
  }
}

///|
/// Whether WebGPU allows `STORAGE_BINDING` usage on this texture format.
pub fn TextureFormat::supports_storage_binding(self : TextureFormat) -> Bool {
  match self {
    RGBA8 | RGBA16F | RGBA32F => true
    _ => false
  }
}

///|
#derive(Eq, Debug)
pub(all) enum Topology {
  TriangleList
  TriangleStrip
  LineList
  LineStrip
  PointList
}

///|
pub fn Topology::code(self : Topology) -> Int {
  match self {
    TriangleList => 0
    TriangleStrip => 1
    LineList => 2
    LineStrip => 3
    PointList => 4
  }
}

///|
pub fn Topology::wgpu_name(self : Topology) -> String {
  match self {
    TriangleList => "triangle-list"
    TriangleStrip => "triangle-strip"
    LineList => "line-list"
    LineStrip => "line-strip"
    PointList => "point-list"
  }
}

///|
#derive(Eq, Debug)
pub(all) enum CullMode {
  None
  Front
  Back
}

///|
pub fn CullMode::wgpu_name(self : CullMode) -> String {
  match self {
    None => "none"
    Front => "front"
    Back => "back"
  }
}

///|
#derive(Eq, Debug)
pub(all) enum FrontFace {
  CounterClockwise
  Clockwise
}

///|
pub fn FrontFace::wgpu_name(self : FrontFace) -> String {
  match self {
    CounterClockwise => "ccw"
    Clockwise => "cw"
  }
}

///|
/// Vertex attribute formats. The ordinals match `wgpu_stub.c`; `wgpu_name()`
/// matches the WebGPU JS specification.
#derive(Eq, Debug)
pub(all) enum VertexFormat {
  Float2
  Float3
  Float4
  Float1
  Int1
  Uint1
  Unorm8x4
  Uint16x4
}

///|
pub fn VertexFormat::code(self : VertexFormat) -> Int {
  match self {
    Float2 => 0
    Float3 => 1
    Float4 => 2
    Float1 => 3
    Int1 => 4
    Uint1 => 5
    Unorm8x4 => 6
    Uint16x4 => 7
  }
}

///|
pub fn VertexFormat::wgpu_name(self : VertexFormat) -> String {
  match self {
    Float1 => "float32"
    Float2 => "float32x2"
    Float3 => "float32x3"
    Float4 => "float32x4"
    Int1 => "sint32"
    Uint1 => "uint32"
    Unorm8x4 => "unorm8x4"
    Uint16x4 => "uint16x4"
  }
}

///|
#derive(Eq, Debug)
pub(all) enum StepMode {
  Vertex
  Instance
}

///|
pub fn StepMode::code(self : StepMode) -> Int {
  match self {
    Vertex => 0
    Instance => 1
  }
}

///|
pub fn StepMode::wgpu_name(self : StepMode) -> String {
  match self {
    Vertex => "vertex"
    Instance => "instance"
  }
}

///|
pub(all) struct VertexAttribute {
  location : Int
  format : VertexFormat
  offset : Int
}

///|
pub fn VertexAttribute::new(
  location : Int,
  format : VertexFormat,
  offset : Int,
) -> VertexAttribute {
  { location, format, offset }
}

///|
pub(all) struct VertexBufferLayout {
  stride : Int
  step_mode : StepMode
  attributes : Array[VertexAttribute]
}

///|
pub fn VertexBufferLayout::new(
  stride : Int,
  attributes : Array[VertexAttribute],
  step_mode? : StepMode = StepMode::Vertex,
) -> VertexBufferLayout {
  { stride, step_mode, attributes }
}

///|
/// Index buffer element width.
#derive(Eq, Debug)
pub(all) enum IndexFormat {
  Uint16
  Uint32
}

///|
pub fn IndexFormat::code(self : IndexFormat) -> Int {
  match self {
    Uint16 => 0
    Uint32 => 1
  }
}

///|
pub fn IndexFormat::wgpu_name(self : IndexFormat) -> String {
  match self {
    Uint16 => "uint16"
    Uint32 => "uint32"
  }
}

///|
/// Composable buffer usage flags; `bits()` is the contract with `wgpu_stub.c`,
/// while `js_bits()` produces standard WebGPU `GPUBufferUsage` bitmasks.
#derive(Eq, Debug)
pub(all) struct BufferUsage {
  priv bits : Int
}

///|
pub fn BufferUsage::none() -> BufferUsage {
  { bits: 0 }
}

///|
pub fn BufferUsage::vertex() -> BufferUsage {
  { bits: 1 }
}

///|
pub fn BufferUsage::index() -> BufferUsage {
  { bits: 2 }
}

///|
pub fn BufferUsage::uniform() -> BufferUsage {
  { bits: 4 }
}

///|
pub fn BufferUsage::storage() -> BufferUsage {
  { bits: 8 }
}

///|
pub fn BufferUsage::indirect() -> BufferUsage {
  { bits: 16 }
}

///|
pub fn BufferUsage::copy_src() -> BufferUsage {
  { bits: 32 }
}

///|
pub fn BufferUsage::copy_dst() -> BufferUsage {
  { bits: 64 }
}

///|
pub fn BufferUsage::combine(
  self : BufferUsage,
  other : BufferUsage,
) -> BufferUsage {
  { bits: self.bits | other.bits }
}

///|
pub fn BufferUsage::contains(self : BufferUsage, other : BufferUsage) -> Bool {
  (self.bits & other.bits) == other.bits
}

///|
pub fn BufferUsage::bits(self : BufferUsage) -> Int {
  self.bits
}

///|
/// Converts to the standard WebGPU `GPUBufferUsage` bitmask (`0x04..0x100`).
pub fn BufferUsage::js_bits(self : BufferUsage) -> Int {
  let mut out = 0
  if self.contains(BufferUsage::copy_src()) {
    out = out | 0x04
  }
  if self.contains(BufferUsage::copy_dst()) {
    out = out | 0x08
  }
  if self.contains(BufferUsage::index()) {
    out = out | 0x10
  }
  if self.contains(BufferUsage::vertex()) {
    out = out | 0x20
  }
  if self.contains(BufferUsage::uniform()) {
    out = out | 0x40
  }
  if self.contains(BufferUsage::storage()) {
    out = out | 0x80
  }
  if self.contains(BufferUsage::indirect()) {
    out = out | 0x100
  }
  out
}

///|
/// Composable texture usage flags; `bits()` is the contract with `wgpu_stub.c`,
/// while `js_bits()` produces standard WebGPU `GPUTextureUsage` bitmasks.
#derive(Eq, Debug)
pub(all) struct TextureUsage {
  priv bits : Int
}

///|
pub fn TextureUsage::none() -> TextureUsage {
  { bits: 0 }
}

///|
pub fn TextureUsage::render_attachment() -> TextureUsage {
  { bits: 1 }
}

///|
pub fn TextureUsage::copy_src() -> TextureUsage {
  { bits: 2 }
}

///|
pub fn TextureUsage::copy_dst() -> TextureUsage {
  { bits: 4 }
}

///|
pub fn TextureUsage::sampled() -> TextureUsage {
  { bits: 8 }
}

///|
pub fn TextureUsage::storage() -> TextureUsage {
  { bits: 16 }
}

///|
pub fn TextureUsage::combine(
  self : TextureUsage,
  other : TextureUsage,
) -> TextureUsage {
  { bits: self.bits | other.bits }
}

///|
pub fn TextureUsage::contains(
  self : TextureUsage,
  other : TextureUsage,
) -> Bool {
  (self.bits & other.bits) == other.bits
}

///|
pub fn TextureUsage::bits(self : TextureUsage) -> Int {
  self.bits
}

///|
/// Converts to the standard WebGPU `GPUTextureUsage` bitmask (`0x01..0x10`).
pub fn TextureUsage::js_bits(self : TextureUsage) -> Int {
  let mut out = 0
  if self.contains(TextureUsage::copy_src()) {
    out = out | 0x01
  }
  if self.contains(TextureUsage::copy_dst()) {
    out = out | 0x02
  }
  if self.contains(TextureUsage::sampled()) {
    out = out | 0x04
  }
  if self.contains(TextureUsage::storage()) {
    out = out | 0x08
  }
  if self.contains(TextureUsage::render_attachment()) {
    out = out | 0x10
  }
  out
}

///|
#derive(Eq, Debug)
pub(all) enum Filter {
  Nearest
  Linear
}

///|
pub fn Filter::code(self : Filter) -> Int {
  match self {
    Nearest => 0
    Linear => 1
  }
}

///|
pub fn Filter::wgpu_name(self : Filter) -> String {
  match self {
    Nearest => "nearest"
    Linear => "linear"
  }
}

///|
/// WebGPU has no border address mode; callers decide whether to reject
/// `ClampToBorder` or clamp to edge.
#derive(Eq, Debug)
pub(all) enum AddressMode {
  Repeat
  ClampToEdge
}

///|
pub fn AddressMode::code(self : AddressMode) -> Int {
  match self {
    Repeat => 0
    ClampToEdge => 1
  }
}

///|
pub fn AddressMode::wgpu_name(self : AddressMode) -> String {
  match self {
    Repeat => "repeat"
    ClampToEdge => "clamp-to-edge"
  }
}

///|
#derive(Eq, Debug)
pub(all) enum CompareOp {
  Never
  Less
  Equal
  LessEqual
  Greater
  NotEqual
  GreaterEqual
  Always
}

///|
pub fn CompareOp::code(self : CompareOp) -> Int {
  match self {
    Never => 0
    Less => 1
    Equal => 2
    LessEqual => 3
    Greater => 4
    NotEqual => 5
    GreaterEqual => 6
    Always => 7
  }
}

///|
pub fn CompareOp::wgpu_name(self : CompareOp) -> String {
  match self {
    Never => "never"
    Less => "less"
    Equal => "equal"
    LessEqual => "less-equal"
    Greater => "greater"
    NotEqual => "not-equal"
    GreaterEqual => "greater-equal"
    Always => "always"
  }
}

///|
#derive(Eq, Debug)
pub(all) enum BlendFactor {
  Zero
  One
  SrcColor
  OneMinusSrcColor
  DstColor
  OneMinusDstColor
  SrcAlpha
  OneMinusSrcAlpha
  DstAlpha
  OneMinusDstAlpha
}

///|
pub fn BlendFactor::wgpu_name(self : BlendFactor) -> String {
  match self {
    Zero => "zero"
    One => "one"
    SrcColor => "src"
    OneMinusSrcColor => "one-minus-src"
    DstColor => "dst"
    OneMinusDstColor => "one-minus-dst"
    SrcAlpha => "src-alpha"
    OneMinusSrcAlpha => "one-minus-src-alpha"
    DstAlpha => "dst-alpha"
    OneMinusDstAlpha => "one-minus-dst-alpha"
  }
}

///|
#derive(Eq, Debug)
pub(all) enum BlendOp {
  Add
  Subtract
  ReverseSubtract
  Min
  Max
}

///|
pub fn BlendOp::wgpu_name(self : BlendOp) -> String {
  match self {
    Add => "add"
    Subtract => "subtract"
    ReverseSubtract => "reverse-subtract"
    Min => "min"
    Max => "max"
  }
}

///|
pub(all) struct BlendState {
  src_color : BlendFactor
  dst_color : BlendFactor
  color_op : BlendOp
  src_alpha : BlendFactor
  dst_alpha : BlendFactor
  alpha_op : BlendOp
}

///|
#derive(Eq, Debug)
pub(all) enum StencilOp {
  Keep
  Zero
  Replace
  IncrementAndClamp
  DecrementAndClamp
  Invert
  IncrementAndWrap
  DecrementAndWrap
}

///|
pub fn StencilOp::wgpu_name(self : StencilOp) -> String {
  match self {
    Keep => "keep"
    Zero => "zero"
    Replace => "replace"
    IncrementAndClamp => "increment-clamp"
    DecrementAndClamp => "decrement-clamp"
    Invert => "invert"
    IncrementAndWrap => "increment-wrap"
    DecrementAndWrap => "decrement-wrap"
  }
}

///|
pub(all) struct StencilFaceState {
  compare : CompareOp
  fail_op : StencilOp
  depth_fail_op : StencilOp
  pass_op : StencilOp
}

///|
pub(all) struct StencilState {
  front : StencilFaceState
  back : StencilFaceState
  read_mask : UInt32
  write_mask : UInt32
}

///|
pub(all) struct DepthStencilState {
  format : TextureFormat
  depth_write : Bool
  depth_compare : CompareOp
  stencil : StencilState?
  depth_bias : Int
  depth_bias_slope : Double
}

///|
pub(all) struct SamplerDesc {
  mag : Filter
  min : Filter
  mipmap : Filter
  address : AddressMode
  min_lod : Float
  max_lod : Float
  anisotropy : Float
  compare : CompareOp?
}

///|
pub fn SamplerDesc::new(
  mag? : Filter = Filter::Linear,
  min? : Filter = Filter::Linear,
  mipmap? : Filter = Filter::Linear,
  address? : AddressMode = AddressMode::ClampToEdge,
  min_lod? : Float = (0.0 : Float),
  max_lod? : Float = (32.0 : Float),
  anisotropy? : Float = (1.0 : Float),
  compare? : CompareOp,
) -> SamplerDesc {
  { mag, min, mipmap, address, min_lod, max_lod, anisotropy, compare }
}

///|
#derive(Eq, Debug)
pub(all) enum LoadOp {
  Clear
  Load
}

///|
pub fn LoadOp::code(self : LoadOp) -> Int {
  match self {
    Clear => 0
    Load => 1
  }
}

///|
pub fn LoadOp::wgpu_name(self : LoadOp) -> String {
  match self {
    Clear => "clear"
    Load => "load"
  }
}

///|
#derive(Eq, Debug)
pub(all) enum StoreOp {
  Store
  Discard
}

///|
pub fn StoreOp::code(self : StoreOp) -> Int {
  match self {
    Store => 1
    Discard => 0
  }
}

///|
pub fn StoreOp::wgpu_name(self : StoreOp) -> String {
  match self {
    Store => "store"
    Discard => "discard"
  }
}

///|
#derive(Eq, Debug)
pub(all) enum Platform {
  Linux
  Windows
  MacOS
}

///|
pub fn Platform::code(self : Platform) -> Int {
  match self {
    Linux => 0
    Windows => 1
    MacOS => 2
  }
}

///|
#derive(Eq, Debug)
pub(all) enum PresentMode {
  Fifo
  Mailbox
  Immediate
}

///|
pub fn PresentMode::code(self : PresentMode) -> Int {
  match self {
    Fifo => 1
    Mailbox => 2
    Immediate => 3
  }
}

///|
/// Packs WGSL UTF-8 source text into a `FixedArray[UInt32]` blob (little-endian
/// words, zero-padded to a 4-byte boundary) so WGSL rides the same shader word
/// channel as SPIR-V and DXIL.
pub fn wgsl_words(source : String) -> FixedArray[UInt32] {
  let bytes = @utf8.encode(source)
  let count = bytes.length()
  let words = FixedArray::make((count + 3) / 4, (0 : UInt32))
  for i = 0; i < count; i = i + 1 {
    let shift = (i % 4) * 8
    words[i / 4] = words[i / 4] | (bytes[i].to_uint() << shift)
  }
  words
}

///|
/// Returns `true` when `words` starts with the SPIR-V magic number `0x07230203`.
pub fn is_spirv_words(words : FixedArray[UInt32]) -> Bool {
  words.length() > 0 && words[0] == (0x07230203 : UInt32)
}

///|
/// Unpacks a little-endian zero-padded `FixedArray[UInt32]` WGSL blob back to
/// UTF-8 text. Works identically on both `native` and `js` targets.
pub fn wgsl_from_words(words : FixedArray[UInt32]) -> String {
  if words.length() == 0 {
    return ""
  }
  let raw_len = words.length() * 4
  let buf = FixedArray::make(raw_len, (0 : Byte))
  for i = 0; i < words.length(); i = i + 1 {
    let v = words[i]
    buf[i * 4] = (v & (0xFF : UInt32)).to_byte()
    buf[i * 4 + 1] = ((v >> 8) & (0xFF : UInt32)).to_byte()
    buf[i * 4 + 2] = ((v >> 16) & (0xFF : UInt32)).to_byte()
    buf[i * 4 + 3] = ((v >> 24) & (0xFF : UInt32)).to_byte()
  }
  let mut end = raw_len
  while end > 0 && buf[end - 1] == (0 : Byte) {
    end = end - 1
  }
  let trimmed = Bytes::makei(end, fn(i) { buf[i] })
  @utf8.decode_lossy(trimmed[:])
}