///|
/// # CLAHE 自适应直方图均衡 clahe
///
/// 图像处理算法模块
/// 图像处理算法模块 Image processing algorithm module
// CLAHE: 对比度受限自适应直方图均衡(纯 MoonBit)

///|
/// CLAHE(Contrast Limited Adaptive Histogram Equalization)。
/// 将图像分成 tile_size × tile_size 的块,每块做直方图均衡,用双线性插值平滑拼接。
/// clip_limit 控制对比度增强强度,值越大增强越强(典型值 2.0~4.0)。
/// 仅处理灰度图(channels=1)或 RGB 图(channels=3/4),alpha 通道不变。
pub fn clahe(
  img : @types.Image,
  tile_size : Int32,
  clip_limit : Float,
) -> @types.Image raise @types.LoadError {
  // 输入验证
  if img.width <= 0 || img.height <= 0 {
    raise @types.LoadError::DecodeFailed("clahe: 图像尺寸必须大于0")
  }
  if img.channels != 1 && img.channels != 3 && img.channels != 4 {
    raise @types.LoadError::DecodeFailed("clahe 仅支持 channels=1/3/4")
  }
  let expected_size = img.width * img.height * img.channels
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "clahe: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  if tile_size < 2 {
    raise @types.LoadError::DecodeFailed("tile_size 必须 >= 2")
  }
  if clip_limit <= 0.0 {
    raise @types.LoadError::DecodeFailed("clip_limit 必须大于0")
  }
  let ch = img.channels
  let color_ch = if ch >= 3 { 3 } else { 1 }
  let n = img.width * img.height
  let out : Array[Byte] = Array::make(n * ch, b'\x00')
  for c in 0.. Unit {
  let w = img.width
  let h = img.height
  let n = w * h
  // 预计算 to_int 数组
  let data_int : Array[Int32] = Array::make(n * ch, 0)
  for i in 0..<(n * ch) {
    data_int[i] = img.data[i].to_int()
  }
  // 块数
  let ntx = (w + tile_size - 1) / tile_size
  let nty = (h + tile_size - 1) / tile_size
  let n_tiles = ntx * nty
  let luts : Array[Array[Int32]] = Array::make(n_tiles, Array::make(256, 0))
  // 计算每块的直方图和 LUT
  for ty in 0.. clip_count {
          excess += hist[i] - clip_count
          hist[i] = clip_count
        }
      }
      // 均匀分配多余的像素
      let redistribute = excess / 256
      let mut remainder = excess - redistribute * 256
      for i in 0..<256 {
        hist[i] += redistribute
        if remainder > 0 {
          hist[i] += 1
          remainder -= 1
        }
      }
      // 计算 CDF 并归一化到 0-255
      let lut = luts[ty * ntx + tx]
      let mut cdf = 0
      for i in 0..<256 {
        cdf += hist[i]
        lut[i] = if tile_pixels > 0 {
          @types.clamp_int(cdf * 255 / tile_pixels, 0, 255)
        } else {
          i
        }
      }
    }
  }
  // 预计算 tile 坐标和权重
  let inv_tile_size = 1.0F / Float::from_int(tile_size)
  let tx_arr : Array[Int32] = Array::make(w, 0)
  let wx_arr : Array[Float] = Array::make(w, 0.0F)
  for x in 0.. Int32 {
  let cx = if tx < 0 { 0 } else if tx >= ntx { ntx - 1 } else { tx }
  let cy = if ty < 0 { 0 } else if ty >= nty { nty - 1 } else { ty }
  cy * ntx + cx
}