///|
pub(all) struct RecordBatch {
  variable : String
  values : Array[Value]
}

///|
fn same_value(left : Value, right : Value) -> Bool {
  match (left, right) {
    (Real(a), Real(b)) if a.is_nan() && b.is_nan() => true
    _ => left == right
  }
}

///|
fn same_values(left : Array[Value], right : Array[Value]) -> Bool {
  if left.length() != right.length() {
    return false
  }
  for index, value in left {
    if !same_value(value, right[index]) {
      return false
    }
  }
  true
}

///|
fn same_attributes(left : Array[Attribute], right : Array[Attribute]) -> Bool {
  if left.length() != right.length() {
    return false
  }
  for attribute in left {
    let found = right
      .iter()
      .find_first(fn(other) { other.name == attribute.name })
    guard found is Some(other) else { return false }
    if attribute.data_type != other.data_type ||
      !same_values(attribute.values, other.values) {
      return false
    }
  }
  true
}

///|
fn unlimited_id(dimensions : Array[Dimension]) -> Int32 raise CdfError {
  for id, dimension in dimensions {
    if dimension.unlimited {
      return id
    }
  }
  raise Invalid("operation requires an unlimited dimension")
}

///|
/// Append complete record slabs to a new file. Omitted record variables are
/// initialized using their own fill values. No bytes of the source are changed.
pub fn Dataset::append(
  self : Dataset,
  count : Int64,
  batches : Array[RecordBatch],
) -> Bytes raise CdfError {
  if count < 0L || count > self.limits.result_values.to_int64() {
    raise ResourceLimit("appended record count exceeds budget")
  }
  let unlimited = unlimited_id(self.dims)
  let changes : Map[String, Array[Value]] = Map([])
  for batch in batches {
    let variable = self.find(batch.variable)
    if !variable.record || changes.contains(variable.name) {
      raise Invalid("append input must name distinct record variables")
    }
    let expected = checked_product(
      count,
      variable.slab_bytes / variable.data_type.width().to_int64(),
      self.limits.result_values.to_int64(),
    )
    if batch.values.length().to_int64() != expected {
      raise Invalid(
        "append values must contain all new slabs for that variable",
      )
    }
    for value in batch.values {
      checked_value(value, variable.data_type)
    }
    changes[variable.name] = batch.values.copy()
  }
  if count > 9223372036854775807L - self.records {
    raise ResourceLimit("record count overflow")
  }
  let document = self.document()
  let dimensions = document.dimensions.copy()
  dimensions[unlimited] = {
    ..dimensions[unlimited],
    length: self.records + count,
  }
  let variables : Array[Variable] = []
  let mut total = 0L
  for variable in document.variables {
    let shape = variable_shape(variable.dimensions, dimensions, self.limits)
    let size = shape_count(shape, self.limits.result_values.to_int64())
    if size > self.limits.result_values.to_int64() - total {
      raise ResourceLimit("append result exceeds aggregate value budget")
    }
    total += size
    if is_record(variable, dimensions) {
      let values = variable.values.copy()
      let added = match changes.get(variable.name) {
        Some(input) => input
        None =>
          Array::make(
            (size - values.length().to_int64()).to_int(),
            fill_for(variable),
          )
      }
      for value in added {
        values.push(value)
      }
      variables.push({ ..variable, values, })
    } else {
      variables.push(variable)
    }
  }
  write_bytes({ ..document, dimensions, variables, }, limits=self.limits)
}

///|
fn matching_schema(left : Dataset, right : Dataset) -> Unit raise CdfError {
  if left.dims.length() != right.dims.length() ||
    left.vars.length() != right.vars.length() ||
    !same_attributes(left.attrs, right.attrs) {
    raise Invalid(
      "concatenation requires matching dimensions, variables and global attributes",
    )
  }
  for id, dimension in left.dims {
    let other = right.dims[id]
    if dimension.name != other.name ||
      dimension.unlimited != other.unlimited ||
      (!dimension.unlimited && dimension.length != other.length) {
      raise Invalid("concatenated dimensions do not match")
    }
  }
  for variable in left.vars {
    let other = right.find(variable.name)
    if variable.data_type != other.data_type ||
      variable.dimensions != other.dimensions ||
      !same_attributes(variable.attributes, other.attributes) {
      raise Invalid(
        "concatenated variable types, axes or attributes do not match",
      )
    }
    if !variable.record &&
      !same_values(left.values(variable.name), right.values(variable.name)) {
      raise Invalid("fixed coordinates or fixed variables differ between files")
    }
  }
}

///|
/// Join compatible files along their unlimited dimension. Fixed coordinates
/// and attributes must match; input ordering determines output record order.
pub fn concatenate(inputs : Array[Dataset]) -> Bytes raise CdfError {
  if inputs.is_empty() || inputs.length() > 64 {
    raise Invalid("concatenation expects between one and 64 input datasets")
  }
  let first = inputs[0]
  let unlimited = unlimited_id(first.dims)
  let mut total_records = 0L
  for input in inputs {
    matching_schema(first, input)
    if input.records > first.limits.result_values.to_int64() - total_records {
      raise ResourceLimit("concatenation exceeds record budget")
    }
    total_records += input.records
  }
  let dimensions = first.dimensions()
  dimensions[unlimited] = { ..dimensions[unlimited], length: total_records, }
  let variables : Array[Variable] = []
  let mut total_values = 0L
  for variable in first.vars {
    let shape = variable_shape(variable.dimensions, dimensions, first.limits)
    let count = shape_count(shape, first.limits.result_values.to_int64())
    if count > first.limits.result_values.to_int64() - total_values {
      raise ResourceLimit("concatenation exceeds aggregate result budget")
    }
    total_values += count
    let values : Array[Value] = []
    if variable.record {
      for input in inputs {
        for value in input.values(variable.name) {
          values.push(value)
        }
      }
    } else {
      for value in first.values(variable.name) {
        values.push(value)
      }
    }
    variables.push({
      name: variable.name,
      data_type: variable.data_type,
      dimensions: variable.dimensions.copy(),
      attributes: variable.attributes.map(copy_attribute),
      values,
    })
  }
  write_bytes(
    {
      format: first.format,
      dimensions,
      attributes: first.attributes(),
      variables,
    },
    limits=first.limits,
  )
}

///|
/// Re-encode using the requested Classic format. Extended CDF-5 integer types
/// require CDF-5 output, even when their particular values are small.
pub fn Dataset::convert(
  self : Dataset,
  format : Format,
) -> Bytes raise CdfError {
  write_bytes({ ..self.document(), format, }, limits=self.limits)
}

///|
pub fn Dataset::with_global_attributes(
  self : Dataset,
  attributes : Array[Attribute],
) -> Bytes raise CdfError {
  write_bytes({ ..self.document(), attributes, }, limits=self.limits)
}