///|
/// # 去雾 dehaze
///
/// 图像处理算法模块
/// 图像处理算法模块 Image processing algorithm module
// 暗通道先验去雾(纯 MoonBit)

///|
/// 暗通道先验去雾(Dark Channel Prior Dehaze)。
/// 基于 He et al. (2009) 的暗通道先验方法。
/// 适用于 RGB/RGBA 图像(channels=3/4)。
/// patch_size 为暗通道计算窗口半径(默认 7),omega 为去雾强度(默认 0.95),
/// t0 为透射率下限(默认 0.1)。
pub fn dehaze(
  img : @types.Image,
  patch_size~ : Int32 = 7,
  omega~ : Float = 0.95F,
  t0~ : Float = 0.1F,
) -> @types.Image raise @types.LoadError {
  // 输入验证
  if img.width < 0 || img.height < 0 {
    raise @types.LoadError::DecodeFailed("dehaze: 图像尺寸不能为负")
  }
  if img.channels != 3 && img.channels != 4 {
    raise @types.LoadError::DecodeFailed("dehaze 需要 RGB/RGBA 图像")
  }
  let expected_size = img.width * img.height * img.channels
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "dehaze: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  if patch_size < 1 || patch_size > 30 {
    raise @types.LoadError::DecodeFailed("patch_size 必须在 1..30 之间")
  }
  if omega <= 0.0F || omega > 1.0F {
    raise @types.LoadError::DecodeFailed("omega 必须在 (0, 1] 之间")
  }
  if t0 <= 0.0F || t0 > 1.0F {
    raise @types.LoadError::DecodeFailed("t0 必须在 (0, 1] 之间")
  }
  let ch = img.channels
  let w = img.width
  let h = img.height
  let n = w * h
  if n == 0 {
    return img
  }
  // 1. 计算暗通道
  let dark_channel = compute_dark_channel(img, w, h, ch, patch_size)
  // 2. 估计大气光 A(取暗通道中最亮的 0.1% 像素对应的原图最亮像素)
  let a = estimate_atmospheric_light(img, dark_channel, w, h, ch)
  let ar = Float::from_int(a[0])
  let ag = Float::from_int(a[1])
  let ab = Float::from_int(a[2])
  // 3. 计算透射率 t = 1 - omega * dark(I/A)
  let transmission : Array[Float] = Array::make(n, 0.0F)
  for i in 0.. Array[Float] {
  let n = w * h
  // 先计算每个像素的最小通道值
  let min_channel : Array[Int32] = Array::make(n, 255)
  for i in 0..= patch_size && y < h - patch_size
    for x in 0..= patch_size && x < w - patch_size {
        continue
      }
      let mut min_val = 255
      let y_start = (y - patch_size).clamp(min=0, max=h - 1)
      let y_end = (y + patch_size).clamp(min=0, max=h - 1)
      let x_start = (x - patch_size).clamp(min=0, max=w - 1)
      let x_end = (x + patch_size).clamp(min=0, max=w - 1)
      for py in y_start..<=y_end {
        for px in x_start..<=x_end {
          if min_channel[py * w + px] < min_val {
            min_val = min_channel[py * w + px]
          }
        }
      }
      dark[y * w + x] = Float::from_int(min_val) / 255.0F
    }
  }
  dark
}

///|
/// 估计大气光
fn estimate_atmospheric_light(
  img : @types.Image,
  dark_channel : Array[Float],
  w : Int32,
  h : Int32,
  ch : Int32,
) -> Array[Int32] {
  let n = w * h
  // 取暗通道中最亮的 0.1% 像素
  let num_pixels = (n / 1000).max(1)
  // 收集暗通道值和索引
  let pairs : Array[(Float, Int32)] = []
  for i in 0.. max_sum {
      max_sum = sum
      max_r = r
      max_g = g
      max_b = b
    }
  }
  [max_r, max_g, max_b]
}

///|
/// 引导滤波(Guided Filter)用于优化透射率。
/// 适用于灰度图(channels=1)作为引导图。
pub fn guided_filter(
  img : @types.Image,
  input : Array[Float],
  radius~ : Int32 = 20,
  eps~ : Float = 0.001F,
) -> Array[Float] raise @types.LoadError {
  // 输入验证
  if img.width < 0 || img.height < 0 {
    raise @types.LoadError::DecodeFailed(
      "guided_filter: 图像尺寸不能为负",
    )
  }
  if img.channels != 1 && img.channels != 3 && img.channels != 4 {
    raise @types.LoadError::DecodeFailed(
      "guided_filter 仅支持 channels=1/3/4",
    )
  }
  let expected_size = img.width * img.height * img.channels
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "guided_filter: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  if radius < 1 {
    raise @types.LoadError::DecodeFailed("guided_filter: radius必须>=1")
  }
  if eps <= 0.0F {
    raise @types.LoadError::DecodeFailed("guided_filter: eps必须大于0")
  }
  let w = img.width
  let h = img.height
  let n = w * h
  if n == 0 || input.length() != n {
    return []
  }
  // 转灰度作为引导图
  let guide : Array[Float] = Array::make(n, 0.0F)
  let ch = img.channels
  for i in 0.. Array[Float] {
  let n = w * h
  let out : Array[Float] = Array::make(n, 0.0F)
  // 内部区域 count 恒为 (2*radius+1)²
  let inner_count = Float::from_int((2 * radius + 1) * (2 * radius + 1))
  for y in radius..<(h - radius) {
    for x in radius..<(w - radius) {
      let mut sum = 0.0F
      for py in (y - radius)..<=(y + radius) {
        for px in (x - radius)..<=(x + radius) {
          sum += data[py * w + px]
        }
      }
      out[y * w + x] = sum / inner_count
    }
  }
  // 边界区域
  for y in 0..= radius && y < h - radius
    for x in 0..= radius && x < w - radius {
        continue
      }
      let mut sum = 0.0F
      let mut count = 0
      let y_start = (y - radius).clamp(min=0, max=h - 1)
      let y_end = (y + radius).clamp(min=0, max=h - 1)
      let x_start = (x - radius).clamp(min=0, max=w - 1)
      let x_end = (x + radius).clamp(min=0, max=w - 1)
      for py in y_start..<=y_end {
        for px in x_start..<=x_end {
          sum += data[py * w + px]
          count += 1
        }
      }
      out[y * w + x] = sum / Float::from_int(count)
    }
  }
  out
}