///|
/// # 色彩量化 16-bit/float 变体 Color quantization 16-bit/float variants
///
/// 16位/浮点色彩量化 quantize_16 / quantize_f
/// 16位/浮点色彩量化 16-bit/float color quantization
// 色彩量化 16-bit/float 变体
// K-means 量化 + Median Cut

///|
fn read_u16_q(data : Bytes, offset : Int32) -> Int32 {
  data[offset].to_int() | (data[offset + 1].to_int() << 8)
}

///|
fn write_u16_q(data : Array[Byte], offset : Int32, v : Int32) -> Unit {
  data[offset] = (v & 0xFF).to_byte()
  data[offset + 1] = ((v >> 8) & 0xFF).to_byte()
}

///|
fn read_f32_q(data : Bytes, offset : Int32) -> Float {
  let b0 = data[offset].to_int()
  let b1 = data[offset + 1].to_int()
  let b2 = data[offset + 2].to_int()
  let b3 = data[offset + 3].to_int()
  let bits = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)
  Float::reinterpret_from_int(bits)
}

///|
fn write_f32_q(data : Array[Byte], offset : Int32, v : Float) -> Unit {
  let bits = v.reinterpret_as_int()
  data[offset] = (bits & 0xFF).to_byte()
  data[offset + 1] = ((bits >> 8) & 0xFF).to_byte()
  data[offset + 2] = ((bits >> 16) & 0xFF).to_byte()
  data[offset + 3] = ((bits >> 24) & 0xFF).to_byte()
}

///|
fn dist_sq_f(
  r1 : Float,
  g1 : Float,
  b1 : Float,
  r2 : Float,
  g2 : Float,
  b2 : Float,
) -> Float {
  let dr = r1 - r2
  let dg = g1 - g2
  let db = b1 - b2
  dr * dr + dg * dg + db * db
}

// ========== K-means 量化 16-bit ==========

///|
/// K-means 色彩量化 16-bit 版本。
/// @see kmeans_quantize 8-bit 版本,本函数为 Image16 变体
pub fn kmeans_quantize_16(
  img : @types.Image16,
  k : Int32,
  max_iters : Int32,
) -> @types.Image16 raise @types.LoadError {
  // 输入验证
  if img.width < 0 || img.height < 0 {
    raise @types.LoadError::DecodeFailed(
      "kmeans_quantize_16: 图像尺寸不能为负",
    )
  }
  if k < 1 || k > 256 {
    raise @types.LoadError::DecodeFailed("k 必须在 1..256 之间")
  }
  if img.channels != 3 && img.channels != 4 {
    raise @types.LoadError::DecodeFailed(
      "kmeans_quantize_16 需要 RGB/RGBA 图像",
    )
  }
  let expected_size = img.width * img.height * img.channels * 2
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "kmeans_quantize_16: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  let ch = img.channels
  let n = img.width * img.height
  if n == 0 {
    return img
  }
  let centroids_r : Array[Int32] = Array::make(k, 0)
  let centroids_g : Array[Int32] = Array::make(k, 0)
  let centroids_b : Array[Int32] = Array::make(k, 0)
  let data_int : Array[Int32] = Array::make(n * ch, 0)
  for i in 0..<(n * ch) {
    data_int[i] = read_u16_q(img.data, i * 2)
  }
  let step = if n > k { n / k } else { 1 }
  for i in 0.. 0 {
        centroids_r[j] = sum_r[j] / cnt[j]
        centroids_g[j] = sum_g[j] / cnt[j]
        centroids_b[j] = sum_b[j] / cnt[j]
      }
    }
  }
  let out : Array[Byte] = Array::make(n * ch * 2, b'\x00')
  for i in 0.. @types.ImageF raise @types.LoadError {
  // 输入验证
  if img.width < 0 || img.height < 0 {
    raise @types.LoadError::DecodeFailed(
      "kmeans_quantize_f: 图像尺寸不能为负",
    )
  }
  if k < 1 || k > 256 {
    raise @types.LoadError::DecodeFailed("k 必须在 1..256 之间")
  }
  if img.channels != 3 && img.channels != 4 {
    raise @types.LoadError::DecodeFailed(
      "kmeans_quantize_f 需要 RGB/RGBA 图像",
    )
  }
  let expected_size = img.width * img.height * img.channels * 4
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "kmeans_quantize_f: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  let ch = img.channels
  let n = img.width * img.height
  if n == 0 {
    return img
  }
  let centroids_r : Array[Float] = Array::make(k, 0.0F)
  let centroids_g : Array[Float] = Array::make(k, 0.0F)
  let centroids_b : Array[Float] = Array::make(k, 0.0F)
  let data_f : Array[Float] = Array::make(n * ch, 0.0F)
  for i in 0..<(n * ch) {
    data_f[i] = read_f32_q(img.data, i * 4)
  }
  let step = if n > k { n / k } else { 1 }
  for i in 0.. 0 {
        centroids_r[j] = sum_r[j] / Float::from_int(cnt[j])
        centroids_g[j] = sum_g[j] / Float::from_int(cnt[j])
        centroids_b[j] = sum_b[j] / Float::from_int(cnt[j])
      }
    }
  }
  let out : Array[Byte] = Array::make(n * ch * 4, b'\x00')
  for i in 0.. @types.Image16 raise @types.LoadError {
  // 输入验证
  if img.width <= 0 || img.height <= 0 {
    raise @types.LoadError::DecodeFailed(
      "floyd_steinberg_16: 图像尺寸必须大于0",
    )
  }
  if img.channels < 1 || img.channels > 4 {
    raise @types.LoadError::DecodeFailed(
      "floyd_steinberg_16: 通道数必须在1-4之间",
    )
  }
  let expected_size = img.width * img.height * img.channels * 2
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "floyd_steinberg_16: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  if levels < 2 {
    raise @types.LoadError::DecodeFailed("floyd_steinberg_16: levels必须>=2")
  }
  let ch = img.channels
  let color_ch = if ch >= 3 { 3 } else { ch }
  let w = img.width
  let h = img.height
  let n = w * h
  let buf : Array[Int32] = Array::make(n * color_ch, 0)
  for i in 0.. 65535 {
          65535
        } else {
          buf[idx]
        }
        let new_val = (old_val + half_step) / step * step
        let new_val_clamped = if new_val < 0 {
          0
        } else if new_val > 65535 {
          65535
        } else {
          new_val
        }
        buf[idx] = new_val_clamped
        let err = old_val - new_val_clamped
        if x + 1 < w {
          buf[(y * w + x + 1) * color_ch + c] += err * 7 / 16
        }
        if y + 1 < h {
          if x > 0 {
            buf[((y + 1) * w + x - 1) * color_ch + c] += err * 3 / 16
          }
          buf[((y + 1) * w + x) * color_ch + c] += err * 5 / 16
          if x + 1 < w {
            buf[((y + 1) * w + x + 1) * color_ch + c] += err / 16
          }
        }
      }
    }
  }
  let out : Array[Byte] = Array::make(n * ch * 2, b'\x00')
  for i in 0.. 65535 {
        65535
      } else {
        buf[i * color_ch + c]
      }
      write_u16_q(out, (i * ch + c) * 2, v)
    }
    if ch == 4 {
      let v = read_u16_q(img.data, (i * ch + 3) * 2)
      write_u16_q(out, (i * ch + 3) * 2, v)
    }
  }
  @types.Image16::{
    width: w,
    height: h,
    channels: ch,
    data: Bytes::from_array(out),
  }
}

// ========== Floyd-Steinberg 抖动 float ==========

///|
/// Floyd-Steinberg 误差扩散抖动量化 float 版本。
/// @see floyd_steinberg 8-bit 版本,本函数为 ImageF 变体
pub fn floyd_steinberg_f(
  img : @types.ImageF,
  levels : Int32,
) -> @types.ImageF raise @types.LoadError {
  // 输入验证
  if img.width <= 0 || img.height <= 0 {
    raise @types.LoadError::DecodeFailed(
      "floyd_steinberg_f: 图像尺寸必须大于0",
    )
  }
  if img.channels < 1 || img.channels > 4 {
    raise @types.LoadError::DecodeFailed(
      "floyd_steinberg_f: 通道数必须在1-4之间",
    )
  }
  let expected_size = img.width * img.height * img.channels * 4
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "floyd_steinberg_f: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  if levels < 2 {
    return img
  }
  let ch = img.channels
  let color_ch = if ch >= 3 { 3 } else { ch }
  let w = img.width
  let h = img.height
  let n = w * h
  let buf : Array[Float] = Array::make(n * color_ch, 0.0F)
  for i in 0.. 1.0F {
          1.0F
        } else {
          buf[idx]
        }
        let new_val = Float::from_int(((old_val + half_step) / step).to_int()) *
          step
        let new_val_clamped = if new_val < 0.0F {
          0.0F
        } else if new_val > 1.0F {
          1.0F
        } else {
          new_val
        }
        buf[idx] = new_val_clamped
        let err = old_val - new_val_clamped
        if x + 1 < w {
          buf[(y * w + x + 1) * color_ch + c] += err * 7.0F / 16.0F
        }
        if y + 1 < h {
          if x > 0 {
            buf[((y + 1) * w + x - 1) * color_ch + c] += err * 3.0F / 16.0F
          }
          buf[((y + 1) * w + x) * color_ch + c] += err * 5.0F / 16.0F
          if x + 1 < w {
            buf[((y + 1) * w + x + 1) * color_ch + c] += err / 16.0F
          }
        }
      }
    }
  }
  let out : Array[Byte] = Array::make(n * ch * 4, b'\x00')
  for i in 0.. 1.0F {
        1.0F
      } else {
        buf[i * color_ch + c]
      }
      write_f32_q(out, (i * ch + c) * 4, v)
    }
    if ch == 4 {
      let v = read_f32_q(img.data, (i * ch + 3) * 4)
      write_f32_q(out, (i * ch + 3) * 4, v)
    }
  }
  @types.ImageF::{
    width: w,
    height: h,
    channels: ch,
    data: Bytes::from_array(out),
  }
}

// ========== Median Cut 辅助函数 16-bit ==========

///|
fn channel_value_mc16(pixel : (Int32, Int32, Int32), ch : Int32) -> Int32 {
  match ch {
    0 => pixel.0
    1 => pixel.1
    _ => pixel.2
  }
}

///|
fn bucket_max_range_mc16(
  pixels : Array[(Int32, Int32, Int32)],
  bucket : Array[Int32],
) -> (Int32, Int32) {
  let mut min_r = 65535
  let mut max_r = 0
  let mut min_g = 65535
  let mut max_g = 0
  let mut min_b = 65535
  let mut max_b = 0
  for i in 0.. max_r {
      max_r = r
    }
    if g < min_g {
      min_g = g
    }
    if g > max_g {
      max_g = g
    }
    if b < min_b {
      min_b = b
    }
    if b > max_b {
      max_b = b
    }
  }
  let range_r = max_r - min_r
  let range_g = max_g - min_g
  let range_b = max_b - min_b
  if range_r >= range_g && range_r >= range_b {
    (range_r, 0)
  } else if range_g >= range_b {
    (range_g, 1)
  } else {
    (range_b, 2)
  }
}

///|
fn bucket_average_mc16(
  pixels : Array[(Int32, Int32, Int32)],
  bucket : Array[Int32],
) -> (Int32, Int32, Int32) {
  let mut sum_r = 0
  let mut sum_g = 0
  let mut sum_b = 0
  for i in 0.. @types.Image16 raise @types.LoadError {
  // 输入验证
  if img.width <= 0 || img.height <= 0 {
    raise @types.LoadError::DecodeFailed(
      "median_cut_16: 图像尺寸必须大于0",
    )
  }
  if img.channels < 1 || img.channels > 4 {
    raise @types.LoadError::DecodeFailed(
      "median_cut_16: 通道数必须在1-4之间",
    )
  }
  let expected_size = img.width * img.height * img.channels * 2
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "median_cut_16: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  if num_colors < 2 {
    raise @types.LoadError::DecodeFailed("median_cut_16: num_colors必须>=2")
  }
  let w = img.width
  let h = img.height
  let n = w * h
  let ch = img.channels
  let pixels : Array[(Int32, Int32, Int32)] = Array::make(n, (0, 0, 0))
  for i in 0..= 2 { read_u16_q(img.data, (i * ch + 1) * 2) } else { r }
    let b = if ch >= 3 { read_u16_q(img.data, (i * ch + 2) * 2) } else { r }
    pixels[i] = (r, g, b)
  }
  let initial_bucket : Array[Int32] = Array::make(n, 0)
  for i in 0.. best_range {
        best_range = range
        best_bucket_idx = bi
      }
    }
    if best_bucket_idx < 0 {
      break
    }
    let bucket = buckets[best_bucket_idx]
    let (_, split_ch) = bucket_max_range_mc16(pixels, bucket)
    let sorted = bucket.copy()
    sorted.sort_by(fn(a, b) {
      let va = channel_value_mc16(pixels[a], split_ch)
      let vb = channel_value_mc16(pixels[b], split_ch)
      va.compare(vb)
    })
    let mid = sorted.length() / 2
    let left : Array[Int32] = Array::make(mid, 0)
    let right : Array[Int32] = Array::make(sorted.length() - mid, 0)
    for i in 0.. Float {
  match ch {
    0 => pixel.0
    1 => pixel.1
    _ => pixel.2
  }
}

///|
fn bucket_max_range_mcf(
  pixels : Array[(Float, Float, Float)],
  bucket : Array[Int32],
) -> (Float, Int32) {
  let mut min_r = 1.0F
  let mut max_r = 0.0F
  let mut min_g = 1.0F
  let mut max_g = 0.0F
  let mut min_b = 1.0F
  let mut max_b = 0.0F
  for i in 0.. max_r {
      max_r = r
    }
    if g < min_g {
      min_g = g
    }
    if g > max_g {
      max_g = g
    }
    if b < min_b {
      min_b = b
    }
    if b > max_b {
      max_b = b
    }
  }
  let range_r = max_r - min_r
  let range_g = max_g - min_g
  let range_b = max_b - min_b
  if range_r >= range_g && range_r >= range_b {
    (range_r, 0)
  } else if range_g >= range_b {
    (range_g, 1)
  } else {
    (range_b, 2)
  }
}

///|
fn bucket_average_mcf(
  pixels : Array[(Float, Float, Float)],
  bucket : Array[Int32],
) -> (Float, Float, Float) {
  let mut sum_r = 0.0F
  let mut sum_g = 0.0F
  let mut sum_b = 0.0F
  for i in 0.. @types.ImageF raise @types.LoadError {
  // 输入验证
  if img.width <= 0 || img.height <= 0 {
    raise @types.LoadError::DecodeFailed(
      "median_cut_f: 图像尺寸必须大于0",
    )
  }
  if img.channels < 1 || img.channels > 4 {
    raise @types.LoadError::DecodeFailed(
      "median_cut_f: 通道数必须在1-4之间",
    )
  }
  let expected_size = img.width * img.height * img.channels * 4
  if img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "median_cut_f: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      img.data.length().to_string(),
    )
  }
  if num_colors < 2 {
    return img
  }
  let w = img.width
  let h = img.height
  let n = w * h
  let ch = img.channels
  let pixels : Array[(Float, Float, Float)] = Array::make(n, (0.0F, 0.0F, 0.0F))
  for i in 0..= 2 { read_f32_q(img.data, (i * ch + 1) * 4) } else { r }
    let b = if ch >= 3 { read_f32_q(img.data, (i * ch + 2) * 4) } else { r }
    pixels[i] = (r, g, b)
  }
  let initial_bucket : Array[Int32] = Array::make(n, 0)
  for i in 0.. best_range {
        best_range = range
        best_bucket_idx = bi
      }
    }
    if best_bucket_idx < 0 {
      break
    }
    let bucket = buckets[best_bucket_idx]
    let (_, split_ch) = bucket_max_range_mcf(pixels, bucket)
    let sorted = bucket.copy()
    sorted.sort_by(fn(a, b) {
      let va = channel_value_mcf(pixels[a], split_ch)
      let vb = channel_value_mcf(pixels[b], split_ch)
      va.compare(vb)
    })
    let mid = sorted.length() / 2
    let left : Array[Int32] = Array::make(mid, 0)
    let right : Array[Int32] = Array::make(sorted.length() - mid, 0)
    for i in 0..