///|
/// # HDR 编码 HDR Encode
///
/// HDR Radiance 格式编码 HDR Radiance format encoding
// 纯 MoonBit HDR 编码(全目标可用:native/wasm/js)
// RGBE 格式编码,使用 RLE 压缩扫描线
// 仅依赖 @types,不依赖 @core/FFI

///|
/// RLE 编码单个通道扫描线
fn rle_encode_scanline_channel(
  channel_data : Array[Byte],
  scanline_len : Int32,
) -> Array[Byte] {
  let out : Array[Byte] = []
  let mut pos = 0
  while pos < scanline_len {
    // 查找重复 run
    let mut run_len = 1
    while pos + run_len < scanline_len &&
          channel_data[pos + run_len] == channel_data[pos] &&
          run_len < 127 {
      run_len += 1
    }
    if run_len >= 4 {
      // RLE 编码
      out.push((128 + run_len).to_byte())
      out.push(channel_data[pos])
      pos += run_len
    } else {
      // 查找非重复 run
      let mut lit_len = 1
      while pos + lit_len < scanline_len && lit_len < 128 {
        // 检查是否开始新的重复 run
        let mut next_run = 0
        while pos + lit_len + next_run < scanline_len &&
              channel_data[pos + lit_len + next_run] ==
              channel_data[pos + lit_len] &&
              next_run < 3 {
          next_run += 1
        }
        if next_run >= 4 {
          break
        }
        lit_len += 1
      }
      // 非重复编码
      out.push(lit_len.to_byte())
      for i in 0.. Bytes raise @types.LoadError {
  if img.channels != 3 {
    raise @types.LoadError::EncodeFailed(
      "HDR 编码需要 3 通道 float 图像",
    )
  }
  let width = img.width
  let height = img.height
  let pixel_count = width * height
  // 构建输出
  let out : Array[Byte] = []
  // 写入 header
  let header_str = "#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n"
  let header_bytes = @encoding/utf8.encode(header_str)
  for i in 0.. 32767 {
    // 小图或大图:不压缩
    for i in 0..<(pixel_count * 4) {
      out.push(rgbe[i])
    }
  } else {
    // RLE 编码
    for y in 0..> 8).to_byte())
      out.push((width & 0xFF).to_byte())
      // 4 通道分别 RLE 编码
      for c in 0..<4 {
        let channel_data : Array[Byte] = []
        for x in 0..