///|
/// # Retinex retinex
///
/// 图像处理算法模块
/// 图像处理算法模块 Image processing algorithm module
// 多尺度 Retinex(纯 MoonBit)

///|
/// Float 自然对数辅助函数
fn logf(x : Float) -> Float {
  Float::from_double(@math.log2(x.to_double()) * 0.6931471805599453)
}

///|
/// 单尺度 Retinex(SSR)。
/// 对每个像素计算 log(I) - log(I * G_sigma),
/// 其中 G_sigma 为高斯滤波器。
/// 适用于灰度图(channels=1)或 RGB/RGBA 图(channels=3/4)。
/// sigma 为高斯标准差,gain 为增益,offset 为偏移。
pub fn ssr(
  img : @types.Image,
  sigma~ : Float = 80.0F,
  gain~ : Float = 1.0F,
  offset~ : Float = 0.0F,
) -> @types.Image raise @types.LoadError {
  // 输入验证
  if img.width == 0 || img.height == 0 {
    return img
  }
  if img.width < 0 || img.height < 0 {
    raise @types.LoadError::DecodeFailed("ssr: 图像尺寸不能为负")
  }
  if img.channels != 1 && img.channels != 3 && img.channels != 4 {
    raise @types.LoadError::DecodeFailed("ssr 仅支持 channels=1/3/4")
  }
  let expected_size = img.width * img.height * img.channels
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "ssr: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  if sigma <= 0.0F {
    raise @types.LoadError::DecodeFailed("sigma 必须 > 0")
  }
  let ch = img.channels
  let w = img.width
  let h = img.height
  let n = w * h
  if n == 0 {
    return img
  }
  let out : Array[Byte] = Array::make(n * ch, b'\x00')
  for c in 0.. 0.0F { blurred[i] } else { 1.0F })
      let retinex = (log_i - log_b) * gain + offset
      let val = (retinex * 30.0F + 128.0F).to_int()
      out[i * ch + c] = val.clamp(min=0, max=255).to_byte()
    }
  }
  @types.Image::{
    width: w,
    height: h,
    channels: ch,
    data: Bytes::from_array(out),
  }
}

///|
/// 多尺度 Retinex(MSR)。
/// 对多个不同 sigma 的 SSR 结果取平均。
/// 适用于灰度图(channels=1)或 RGB/RGBA 图(channels=3/4)。
/// sigmas 为高斯标准差数组(默认 [15, 80, 250])。
/// gain 为增益,offset 为偏移。
pub fn msr(
  img : @types.Image,
  sigmas~ : Array[Float] = [15.0F, 80.0F, 250.0F],
  gain~ : Float = 1.0F,
  offset~ : Float = 0.0F,
) -> @types.Image raise @types.LoadError {
  // 输入验证
  if img.width == 0 || img.height == 0 {
    return img
  }
  if img.width < 0 || img.height < 0 {
    raise @types.LoadError::DecodeFailed("msr: 图像尺寸不能为负")
  }
  if img.channels != 1 && img.channels != 3 && img.channels != 4 {
    raise @types.LoadError::DecodeFailed("msr 仅支持 channels=1/3/4")
  }
  let expected_size = img.width * img.height * img.channels
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "msr: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  if sigmas.length() == 0 {
    raise @types.LoadError::DecodeFailed("sigmas 不能为空")
  }
  for s in sigmas {
    if s <= 0.0F {
      raise @types.LoadError::DecodeFailed("sigma 必须 > 0")
    }
  }
  let ch = img.channels
  let w = img.width
  let h = img.height
  let n = w * h
  if n == 0 {
    return img
  }
  let out : Array[Byte] = Array::make(n * ch, b'\x00')
  let num_scales = sigmas.length()
  for c in 0.. 0.0F { blurred[i] } else { 1.0F })
        retinex_sum[i] += log_channel[i] - log_b
      }
    }
    let inv_scales = gain / Float::from_int(num_scales)
    for i in 0.. @types.Image raise @types.LoadError {
  if img.channels != 3 && img.channels != 4 {
    raise @types.LoadError::DecodeFailed("msrcr 需要 RGB/RGBA 图像")
  }
  if sigmas.length() == 0 {
    raise @types.LoadError::DecodeFailed("sigmas 不能为空")
  }
  let ch = img.channels
  let w = img.width
  let h = img.height
  let n = w * h
  if n == 0 {
    return img
  }
  let out : Array[Byte] = Array::make(n * ch, b'\x00')
  let num_scales = sigmas.length()
  // 提取各通道
  let channels : Array[Array[Float]] = [
    Array::make(n, 0.0F),
    Array::make(n, 0.0F),
    Array::make(n, 0.0F),
  ]
  for c in 0..<3 {
    for i in 0.. 0.0F { blurred[i] } else { 1.0F })
        retinex_sum[i] += log_channel[i] - log_b
      }
    }
    let inv_scales = 1.0F / Float::from_int(num_scales)
    for i in 0.. Array[Float] {
  let n = w * h
  let out : Array[Float] = Array::make(n, 0.0F)
  let radius = (Float::from_int(3) * sigma).to_int()
  let radius = if radius < 1 { 1 } else { radius }
  let kernel_size = 2 * radius + 1
  let kernel : Array[Float] = Array::make(kernel_size, 0.0F)
  let two_sigma_sq = 2.0F * sigma * sigma
  let mut kernel_sum = 0.0F
  for i in 0..= w {
    // 大 radius:所有像素都是边界,用 prefix sum 将 O(kernel_size) 降为 O(w)
    for y in 0.. 0 { left_end } else { 0 }
        let mid_end = if right_start < kernel_size {
          right_start
        } else {
          kernel_size
        }
        let mut sum = c0 * k_prefix[mid_start] +
          cw1 * (total_k - k_prefix[mid_end])
        for k in mid_start..= radius && x < w - radius {
          continue
        }
        let mut sum = 0.0F
        for k in -radius..<=radius {
          let px = (x + k).clamp(min=0, max=w - 1)
          sum += channel[row_base + px] * kernel[k + radius]
        }
        temp[row_base + x] = sum
      }
    }
  }
  // 垂直模糊
  if radius >= h {
    // 大 radius:用 prefix sum 优化
    for x in 0.. 0 { left_end } else { 0 }
        let mid_end = if right_start < kernel_size {
          right_start
        } else {
          kernel_size
        }
        let mut sum = c0 * k_prefix[mid_start] +
          ch1 * (total_k - k_prefix[mid_end])
        for k in mid_start..= radius && y < h - radius {
          continue
        }
        let mut sum = 0.0F
        for k in -radius..<=radius {
          let py = (y + k).clamp(min=0, max=h - 1)
          sum += temp[py * w + x] * kernel[k + radius]
        }
        out[y * w + x] = sum
      }
    }
  }
  out
}