// Pure MoonBit port of stb_image_write v1.19 Radiance RGBE HDR writer.

///|
/// Binary exponent of a normal double in `frexp` convention: for
/// `x = m * 2^exp` with `m` in `[0.5, 1)`, return `exp`.
fn stbiw_frexp_exp(x : Double) -> Int {
  let bits = x.reinterpret_as_uint64()
  let raw = ((bits >> 52) & (0x7FF : UInt64)).reinterpret_as_int64().to_int()
  raw - 1022
}

///|
/// Convert linear RGB floats to one RGBE pixel (`stbiw__linear_to_rgbe`).
fn stbiw_linear_to_rgbe(
  rgbe : FixedArray[Byte],
  pixel : FixedArray[Float],
  offset : Int,
  ncomp : Int,
) -> Unit {
  let mut r : Double = 0.0
  let mut g : Double = 0.0
  let mut b : Double = 0.0
  let mut maxcomp : Double = 0.0
  if ncomp >= 3 {
    r = pixel[offset].to_double()
    g = pixel[offset + 1].to_double()
    b = pixel[offset + 2].to_double()
    maxcomp = if r > g { r } else { g }
    maxcomp = if maxcomp > b { maxcomp } else { b }
  } else {
    r = pixel[offset].to_double()
    g = r
    b = r
    maxcomp = r
  }
  let flt_max : Double = 3.4028234663852886e38
  if maxcomp >= flt_max {
    r = if r < flt_max { r } else { flt_max }
    g = if g < flt_max { g } else { flt_max }
    b = if b < flt_max { b } else { flt_max }
    maxcomp = flt_max
  }
  if maxcomp <= 1.0e-32 {
    rgbe[0] = (0 : Byte)
    rgbe[1] = (0 : Byte)
    rgbe[2] = (0 : Byte)
    rgbe[3] = (0 : Byte)
  } else {
    let exp = stbiw_frexp_exp(maxcomp)
    let normalize = 256.0 / @math.pow(2.0, exp.to_double())
    rgbe[0] = ((if r > 0.0 { (r * normalize).to_int() } else { 0 }) & 0xFF).to_byte()
    rgbe[1] = ((if g > 0.0 { (g * normalize).to_int() } else { 0 }) & 0xFF).to_byte()
    rgbe[2] = ((if b > 0.0 { (b * normalize).to_int() } else { 0 }) & 0xFF).to_byte()
    rgbe[3] = ((exp + 128) & 0xFF).to_byte()
  }
}

///|
/// Write one RLE run packet (`stbiw__write_run_data`).
fn stbiw_hdr_write_run(w : StbiwWriter, length : Int, databyte : Byte) -> Unit {
  w.write_u8(length + 128)
  w.write_byte(databyte)
}

///|
/// Write one RLE dump packet (`stbiw__write_dump_data`).
fn stbiw_hdr_write_dump(
  w : StbiwWriter,
  scratch : FixedArray[Byte],
  start : Int,
  length : Int,
) -> Unit {
  w.write_u8(length)
  for i = 0; i < length; i = i + 1 {
    w.write_byte(scratch[start + i])
  }
}

///|
/// Write one scanline as raw or RLE RGBE (`stbiw__write_hdr_scanline`).
fn stbiw_hdr_write_scanline(
  w : StbiwWriter,
  width : Int,
  ncomp : Int,
  scratch : FixedArray[Byte],
  scanline : FixedArray[Float],
  row_offset : Int,
) -> Unit {
  let rgbe : FixedArray[Byte] = FixedArray::make(4, (0 : Byte))
  if width < 8 || width >= 32768 {
    for x = 0; x < width; x = x + 1 {
      stbiw_linear_to_rgbe(rgbe, scanline, row_offset + x * ncomp, ncomp)
      for c = 0; c < 4; c = c + 1 {
        w.write_byte(rgbe[c])
      }
    }
    return
  }
  for x = 0; x < width; x = x + 1 {
    stbiw_linear_to_rgbe(rgbe, scanline, row_offset + x * ncomp, ncomp)
    for c = 0; c < 4; c = c + 1 {
      scratch[x + width * c] = rgbe[c]
    }
  }
  w.write_u8(2)
  w.write_u8(2)
  w.write_u8((width & 0xFF00) >> 8)
  w.write_u8(width & 0xFF)
  for c = 0; c < 4; c = c + 1 {
    let comp = width * c
    let mut x = 0
    while x < width {
      // find first run of three equal bytes
      let mut r = x
      while r + 2 < width {
        if scratch[comp + r] == scratch[comp + r + 1] &&
          scratch[comp + r] == scratch[comp + r + 2] {
          break
        }
        r += 1
      }
      if r + 2 >= width {
        r = width
      }
      while x < r {
        let mut len = r - x
        if len > 128 {
          len = 128
        }
        stbiw_hdr_write_dump(w, scratch, comp + x, len)
        x += len
      }
      if r + 2 < width {
        while r < width && scratch[comp + r] == scratch[comp + x] {
          r += 1
        }
        while x < r {
          let mut len = r - x
          if len > 127 {
            len = 127
          }
          stbiw_hdr_write_run(w, len, scratch[comp + x])
          x += len
        }
      }
    }
  }
}

///|
/// Encode linear RGB floats as a Radiance `.hdr` file in memory.
///
/// `comp` is 1 (luminance) or >= 3 (RGB). `stride_in_floats` is 0 for a
/// tightly packed image, otherwise the row pitch in floats.
pub fn stbi_write_hdr_to_memory(
  width : Int,
  height : Int,
  comp : Int,
  data : FixedArray[Float],
  stride_in_floats? : Int = 0,
  options? : StbiwOptions,
) -> Bytes? {
  let opts = match options {
    Some(o) => o
    None => StbiwOptions::default()
  }
  let stride = match stbiw_resolve_float_stride(
    width,
    height,
    comp,
    stride_in_floats,
    data.length(),
  ) {
    Some(s) => s
    None => return None
  }
  let scratch : FixedArray[Byte] = FixedArray::make(width * 4, (0 : Byte))
  let w = StbiwWriter::new(capacity=128 + width * height * 4)
  w.write_ascii("#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n")
  w.write_ascii("EXPOSURE=          1.0000000000000\n\n-Y ")
  w.write_ascii(height.to_string())
  w.write_ascii(" +X ")
  w.write_ascii(width.to_string())
  w.write_ascii("\n")
  for i = 0; i < height; i = i + 1 {
    let row = if opts.flip_vertically { height - 1 - i } else { i }
    stbiw_hdr_write_scanline(w, width, comp, scratch, data, row * stride)
  }
  Some(w.to_bytes())
}