///|
pub(all) enum Reduction {
  Mean
  Minimum
  Maximum
  Sum
  Count
  PopulationStddev
} derive(Eq)

///|
pub extend Reduction with Eq::{equal, not_equal}

///|
pub struct ReducedData {
  shape : Array[Int64]
  values : Array[Double?]
  counts : Array[Int32]
}

///|
/// Reduce any combination of axes in stored row-major order. Missing values do
/// not contribute. A group with no present values yields None (Count yields 0).
/// Sum/stddev overflow is reported instead of emitting a misleading finite value.
pub fn reduce_physical(
  shape : Array[Int64],
  values : Array[Double?],
  axes : Array[Int32],
  reduction : Reduction,
  keep_dimensions~ : Bool = false,
) -> ReducedData raise CdfError {
  if shape.length() > 16 ||
    shape_count(shape, 1000000L) != values.length().to_int64() {
    raise Invalid("reduction shape does not match its values")
  }
  let reduced = Array::make(shape.length(), false)
  for axis in axes {
    if axis < 0 || axis >= shape.length() || reduced[axis] {
      raise Invalid("reduction axes must be distinct valid axis indices")
    }
    reduced[axis] = true
  }
  let output_shape : Array[Int64] = []
  for axis, extent in shape {
    if reduced[axis] {
      if keep_dimensions {
        output_shape.push(1L)
      }
    } else {
      output_shape.push(extent)
    }
  }
  let size = shape_count(output_shape, 1000000L).to_int()
  if size == 0 {
    return { shape: output_shape, values: [], counts: [], }
  }
  let counts = Array::make(size, 0)
  let sums = Array::make(size, 0.0)
  let corrections = Array::make(size, 0.0)
  let means = Array::make(size, 0.0)
  let moment_size = if reduction == PopulationStddev { size } else { 0 }
  let moments = Array::make(moment_size, 0.0)
  let moment_scales = Array::make(moment_size, 0.0)
  let moment_anchors = Array::make(moment_size, 0.0)
  let moment_means = Array::make(moment_size, 0.0)
  let minimum = Array::make(size, 0.0)
  let maximum = Array::make(size, 0.0)
  let input_strides = row_strides(shape)
  let output_weights = Array::make(shape.length(), 0L)
  let mut weight = 1L
  for axis = shape.length() - 1; axis >= 0; axis = axis - 1 {
    if !reduced[axis] {
      output_weights[axis] = weight
      weight = checked_product(weight, shape[axis], 1000000L)
    }
  }
  for index, optional in values {
    if optional is Some(number) {
      if number.is_nan() || number.is_inf() {
        raise Invalid("reduction requires finite or explicit missing values")
      }
      let mut group = 0L
      for axis, extent in shape {
        if !reduced[axis] {
          group += index.to_int64() /
            input_strides[axis] %
            extent *
            output_weights[axis]
        }
      }
      let g = group.to_int()
      let previous = counts[g]
      counts[g] += 1
      if previous == 0 {
        minimum[g] = number
        maximum[g] = number
        if reduction == PopulationStddev {
          moment_anchors[g] = number
        }
      } else {
        minimum[g] = minimum[g].min(number)
        maximum[g] = maximum[g].max(number)
      }
      let old_mean = means[g]
      means[g] = weighted_mean(old_mean, previous, number, 1)
      if reduction == PopulationStddev && previous > 0 {
        let (new_scale, mean, sum, correction) = centered_moment(
          moment_anchors[g],
          moment_scales[g],
          moment_means[g],
          moments[g],
          corrections[g],
          number,
          counts[g],
        )
        moment_scales[g] = new_scale
        moment_means[g] = mean
        moments[g] = sum
        corrections[g] = correction
      }
      if reduction == Sum {
        let corrected = number - corrections[g]
        let next = sums[g] + corrected
        corrections[g] = next - sums[g] - corrected
        sums[g] = next
      }
    }
  }
  let output = Array::makei(size, group => {
    if reduction == Count {
      return Some(counts[group].to_double())
    }
    if counts[group] == 0 {
      return None
    }
    let result = match reduction {
      Mean => means[group]
      Minimum => minimum[group]
      Maximum => maximum[group]
      Sum => sums[group]
      Count => counts[group].to_double()
      PopulationStddev =>
        match
          moment_stddev(moment_scales[group], moments[group], counts[group]) {
          Some(value) => value
          None => raise Unsupported("standard deviation exceeds Float64 range")
        }
    }
    if result.is_nan() || result.is_inf() {
      raise Unsupported(
        "reduction overflow: rescale the input before aggregating",
      )
    }
    Some(result)
  })
  { shape: output_shape, values: output, counts, }
}

///|
/// Select an inclusive range of a one-dimensional monotonic coordinate variable.
/// Ascending and descending order are supported. No sorting, cyclic-longitude
/// wrapping, unit conversion or interpolation is performed implicitly.
pub fn Dataset::coordinate_window(
  self : Dataset,
  dimension : String,
  lower : Double,
  upper : Double,
  stride~ : Int64 = 1L,
) -> AxisSelection raise CdfError {
  if lower.is_nan() ||
    lower.is_inf() ||
    upper.is_nan() ||
    upper.is_inf() ||
    lower > upper ||
    stride < 1L {
    raise Invalid(
      "coordinate bounds must be finite, ordered, and use a positive stride",
    )
  }
  let coordinate = self.find(dimension)
  if coordinate.dimensions.length() != 1 ||
    self.dims[coordinate.dimensions[0]].name != dimension {
    raise Invalid(
      "coordinate variable must have the same name as its only dimension",
    )
  }
  let values = self.physical_section(dimension, [0L], coordinate.shape).values
  let coordinates = values.map(value => {
    match value {
      Some(number) => number
      None => raise Invalid("coordinate contains a missing or invalid value")
    }
  })
  let size = coordinates.length()
  if size == 0 {
    return { dimension, start: 0L, count: 0L, stride, }
  }
  let ascending = size == 1 || coordinates[size - 1] > coordinates[0]
  for i in 1..= coordinates[i - 1]) {
      raise Invalid("coordinate must be strictly monotonic")
    }
  }
  // Use binary searches after checking monotonicity. Returned indices retain the
  // original storage order, including descending latitude grids.
  fn lower_bound(needle : Double, strict : Bool) -> Int32 {
    let mut left = 0
    let mut right = size
    while left < right {
      let mid = left + (right - left) / 2
      let before = if ascending {
        coordinates[mid] < needle || (strict && coordinates[mid] == needle)
      } else {
        coordinates[mid] > needle || (strict && coordinates[mid] == needle)
      }
      if before {
        left = mid + 1
      } else {
        right = mid
      }
    }
    left
  }
  let start = lower_bound(if ascending { lower } else { upper }, false)
  let end = lower_bound(if ascending { upper } else { lower }, true)
  let count = if end <= start {
    0L
  } else {
    (end - start - 1).to_int64() / stride + 1L
  }
  { dimension, start: start.to_int64(), count, stride, }
}