///|
pub struct DataBlock {
  data_type : DataType
  shape : Array[Int64]
  values : Array[Value]
}

///|
pub(all) struct AxisSelection {
  dimension : String
  start : Int64
  count : Int64
  stride : Int64
}

///|
fn validate_section(
  shape : Array[Int64],
  start : Array[Int64],
  count : Array[Int64],
  stride : Array[Int64],
  limit : Int32,
) -> Int32 raise CdfError {
  if start.length() != shape.length() ||
    count.length() != shape.length() ||
    stride.length() != shape.length() {
    raise Invalid("section vectors must match the variable rank")
  }
  for axis, extent in shape {
    if start[axis] < 0L ||
      start[axis] > extent ||
      count[axis] < 0L ||
      stride[axis] < 1L {
      raise Invalid("invalid section origin, extent or stride")
    }
    if count[axis] > 0L &&
      (
        start[axis] == extent ||
        count[axis] - 1L > (extent - start[axis] - 1L) / stride[axis]
      ) {
      raise Invalid("section extends beyond the selected axis")
    }
  }
  shape_count(count, limit.to_int64()).to_int()
}

///|
fn row_strides(shape : Array[Int64]) -> Array[Int64] raise CdfError {
  if shape.any(extent => extent == 0L) {
    return Array::make(shape.length(), 0L)
  }
  let strides = Array::make(shape.length(), 1L)
  let mut stride = 1L
  for axis = shape.length() - 1; axis >= 0; axis = axis - 1 {
    strides[axis] = stride
    stride = checked_product(stride, shape[axis], 9223372036854775807L)
  }
  strides
}

///|
fn section_index(
  index : Int32,
  count : Array[Int64],
  start : Array[Int64],
  step : Array[Int64],
  strides : Array[Int64],
) -> Int64 {
  let mut remainder = index.to_int64()
  let mut source_index = 0L
  for axis = count.length() - 1; axis >= 0; axis = axis - 1 {
    let coordinate = remainder % count[axis]
    remainder /= count[axis]
    source_index += (start[axis] + coordinate * step[axis]) * strides[axis]
  }
  source_index
}

///|
/// Read only selected values. start/count/stride use the stored axis order,
/// with the last axis varying fastest. An empty count selects no values.
pub fn Dataset::section(
  self : Dataset,
  name : String,
  start : Array[Int64],
  count : Array[Int64],
  stride~ : Array[Int64] = [],
) -> DataBlock raise CdfError {
  let variable = self.find(name)
  let stride = if stride.is_empty() {
    Array::make(variable.shape.length(), 1L)
  } else {
    stride
  }
  let size = validate_section(
    variable.shape,
    start,
    count,
    stride,
    self.limits.result_values,
  )
  let strides = row_strides(variable.shape)
  let values = Array::makei(size, index => {
    self.value_at(variable, section_index(index, count, start, stride, strides))
  })
  { data_type: variable.data_type, shape: count.copy(), values, }
}

///|
/// Subset shared dimensions consistently across all variables, including
/// coordinate variables. The returned file is an independent complete result.
pub fn Dataset::subset(
  self : Dataset,
  selections : Array[AxisSelection],
) -> Bytes raise CdfError {
  let chosen : Map[String, AxisSelection] = Map([])
  for selection in selections {
    let name = checked_name(selection.dimension, self.limits)
    if chosen.contains(name) || !self.dims.any(d => d.name == name) {
      raise Invalid("unknown or duplicate selected dimension")
    }
    chosen[name] = { ..selection, dimension: name, }
  }
  let dimensions = self.dims.map(dimension => {
    match chosen.get(dimension.name) {
      None => dimension
      Some(selection) => {
        let _ = validate_section(
          [dimension.length],
          [selection.start],
          [selection.count],
          [selection.stride],
          self.limits.result_values,
        )
        if selection.count == 0L && !dimension.unlimited {
          raise Invalid("Classic cannot encode a zero-length fixed dimension")
        }
        { ..dimension, length: selection.count, }
      }
    }
  })
  let variables : Array[Variable] = []
  let mut remaining = self.limits.result_values
  for variable in self.vars {
    let start = Array::make(variable.shape.length(), 0L)
    let count = variable.shape.copy()
    let stride = Array::make(variable.shape.length(), 1L)
    for axis, id in variable.dimensions {
      if chosen.get(self.dims[id].name) is Some(selection) {
        start[axis] = selection.start
        count[axis] = selection.count
        stride[axis] = selection.stride
      }
    }
    let size = validate_section(variable.shape, start, count, stride, remaining)
    remaining -= size
    let block = self.section(variable.name, start, count, stride~)
    variables.push({
      name: variable.name,
      data_type: variable.data_type,
      dimensions: variable.dimensions.copy(),
      attributes: variable.attributes.map(copy_attribute),
      values: block.values,
    })
  }
  write_bytes(
    {
      format: self.format,
      dimensions,
      attributes: self.attributes(),
      variables,
    },
    limits=self.limits,
  )
}

///|
/// Apply replacement values to an existing region without modifying the input
/// Dataset or caller-owned arrays. All indices are checked before encoding.
pub fn Dataset::replace_section(
  self : Dataset,
  name : String,
  start : Array[Int64],
  count : Array[Int64],
  values : Array[Value],
  stride~ : Array[Int64] = [],
) -> Bytes raise CdfError {
  let selected = self.find(name)
  let step = if stride.is_empty() {
    Array::make(selected.shape.length(), 1L)
  } else {
    stride
  }
  let size = validate_section(
    selected.shape,
    start,
    count,
    step,
    self.limits.result_values,
  )
  if size != values.length() {
    raise Invalid("replacement length does not match the selected region")
  }
  for value in values {
    checked_value(value, selected.data_type)
  }
  let strides = row_strides(selected.shape)
  let document = self.document()
  for index, variable in document.variables {
    if variable.name == selected.name {
      let updated = variable.values.copy()
      for i, value in values {
        updated[section_index(i, count, start, step, strides).to_int()] = value
      }
      document.variables[index] = { ..variable, values: updated, }
    }
  }
  write_bytes(document, limits=self.limits)
}

///|
/// Permute a block's axes. This changes array order only, retaining the type
/// and exact stored values, including 64-bit integers and floating NaNs.
pub fn transpose(
  block : DataBlock,
  axes : Array[Int32],
) -> DataBlock raise CdfError {
  if block.shape.length() > 16 ||
    axes.length() != block.shape.length() ||
    shape_count(block.shape, 1000000L) != block.values.length().to_int64() {
    raise Invalid("invalid block shape or permutation rank")
  }
  let seen = Array::make(axes.length(), false)
  for axis in axes {
    if axis < 0 || axis >= axes.length() || seen[axis] {
      raise Invalid("axis permutation must contain every axis once")
    }
    seen[axis] = true
  }
  let shape = axes.map(axis => block.shape[axis])
  let old_strides = row_strides(block.shape)
  let strides = axes.map(axis => old_strides[axis])
  let origin = Array::make(shape.length(), 0L)
  let step = Array::make(shape.length(), 1L)
  let values = Array::makei(block.values.length(), fn(index) {
    block.values[section_index(index, shape, origin, step, strides).to_int()]
  })
  { data_type: block.data_type, shape, values, }
}