///|
pub struct VariableInfo {
  name : String
  data_type : DataType
  dimensions : Array[Int32]
  shape : Array[Int64]
  attributes : Array[Attribute]
  offset : Int64
  slab_bytes : Int64
  padded_bytes : Int64
  record : Bool
}

///|
pub struct Dataset {
  format : Format
  records : Int64
  streaming : Bool
  header_bytes : Int32
  record_bytes : Int64
  priv source : Bytes
  priv dims : Array[Dimension]
  priv attrs : Array[Attribute]
  priv vars : Array[VariableInfo]
  priv limits : Limits
}

///|
priv struct HeaderBudget {
  mut remaining : Int32
  mut value_remaining : Int32
}

///|
fn list_count(
  input : Cursor,
  format : Format,
  tag : Int32,
  budget : HeaderBudget,
) -> Int32 raise CdfError {
  let found = input.uint(4)
  let count = input.small_count(format, budget.remaining)
  if found == 0UL {
    if count != 0 {
      raise Invalid("an absent list must have a zero element count")
    }
  } else if found != tag.to_uint64() {
    raise Invalid("invalid header list tag at byte \{input.position}")
  }
  budget.remaining -= count
  count
}

///|
fn copy_attribute(attribute : Attribute) -> Attribute {
  { ..attribute, values: attribute.values.copy(), }
}

///|
fn copy_info(variable : VariableInfo) -> VariableInfo {
  {
    ..variable,
    dimensions: variable.dimensions.copy(),
    shape: variable.shape.copy(),
    attributes: variable.attributes.map(copy_attribute),
  }
}

///|
fn read_attributes(
  input : Cursor,
  format : Format,
  limits : Limits,
  budget : HeaderBudget,
) -> Array[Attribute] raise CdfError {
  let count = list_count(input, format, 12, budget)
  let attributes : Array[Attribute] = []
  let names : Map[String, Bool] = Map([])
  for _ in 0.. input.value(kind))
    input.padding(bytes.to_int())
    attributes.push({ name, data_type: kind, values, })
  }
  attributes
}

///|
fn validate_fill(
  attributes : Array[Attribute],
  kind : DataType,
) -> Unit raise CdfError {
  for attribute in attributes {
    if attribute.name == "_FillValue" &&
      (attribute.data_type != kind || attribute.values.length() != 1) {
      raise Invalid(
        "_FillValue must be a scalar of the variable's storage type",
      )
    }
  }
}

///|
fn variable_shape(
  ids : Array[Int32],
  dims : Array[Dimension],
  limits : Limits,
) -> Array[Int64] raise CdfError {
  if ids.length() > limits.rank {
    raise ResourceLimit("variable rank exceeds budget")
  }
  let shape : Array[Int64] = []
  for axis, id in ids {
    if id < 0 || id >= dims.length() {
      raise Invalid("variable references a missing dimension")
    }
    if dims[id].unlimited && axis != 0 {
      raise Invalid("unlimited dimension must be the first variable dimension")
    }
    shape.push(dims[id].length)
  }
  shape
}

///|
fn shape_count(shape : Array[Int64], limit : Int64) -> Int64 raise CdfError {
  if limit < 0L {
    raise ResourceLimit("shape budget cannot be negative")
  }
  let mut empty = false
  for extent in shape {
    if extent < 0L {
      raise Invalid("shape extents cannot be negative")
    }
    empty = empty || extent == 0L
  }
  if empty {
    return 0L
  }
  let mut count = checked_product(1L, 1L, limit)
  for extent in shape {
    count = checked_product(count, extent, limit)
  }
  count
}

///|
fn read_header(
  input : Cursor,
  format : Format,
  num_records : Int64,
  limits : Limits,
) -> (Array[Dimension], Array[Attribute], Array[VariableInfo]) raise CdfError {
  let budget = HeaderBudget::{
    remaining: limits.header_items,
    value_remaining: limits.result_values,
  }
  let dim_count = list_count(input, format, 10, budget)
  let dims : Array[Dimension] = []
  let dim_names : Map[String, Bool] = Map([])
  let mut has_unlimited = false
  for _ in 0.. input.small_count(format, dim_count))
    let shape = variable_shape(ids, dims, limits)
    let attributes = read_attributes(input, format, limits, budget)
    let kind = data_type(input.uint(4).to_int(), format)
    validate_fill(attributes, kind)
    let stored_size = input.count(format)
    let offset = if format == Cdf1 {
      input.uint(4).reinterpret_as_int64()
    } else {
      let raw = input.uint(8)
      if raw > 9223372036854775807UL {
        raise ResourceLimit("variable offset exceeds addressable range")
      }
      raw.reinterpret_as_int64()
    }
    let record = !ids.is_empty() && dims[ids[0]].unlimited
    let slab_shape = if record { shape[1:].to_owned() } else { shape }
    let slab_values = shape_count(slab_shape, limits.file_bytes.to_int64())
    let slab_bytes = checked_product(
      slab_values,
      kind.width().to_int64(),
      limits.file_bytes.to_int64(),
    )
    let padded_bytes = padded4(slab_bytes)
    if stored_size != padded_bytes {
      raise Invalid("vsize disagrees with dimensions and external type")
    }
    if offset % 4L != 0L {
      raise Invalid("variable begins at an unaligned offset")
    }
    vars.push({
      name,
      data_type: kind,
      dimensions: ids,
      shape,
      attributes,
      offset,
      slab_bytes,
      padded_bytes,
      record,
    })
  }
  (dims, attrs, vars)
}

///|
fn validate_layout(
  vars : Array[VariableInfo],
  header_bytes : Int32,
  records : Int64,
  source_bytes : Int32,
) -> (Int64, Int64) raise CdfError {
  let mut fixed_end = header_bytes.to_int64()
  let record_vars : Array[VariableInfo] = []
  for variable in vars {
    if variable.record {
      record_vars.push(variable)
    } else {
      if variable.offset < fixed_end ||
        variable.offset > source_bytes.to_int64() ||
        variable.slab_bytes > source_bytes.to_int64() - variable.offset {
        raise Truncated(
          "fixed variable range is outside data or overlaps earlier data",
        )
      }
      fixed_end = variable.offset + variable.padded_bytes
    }
  }
  if record_vars.is_empty() {
    if records != 0L {
      raise Invalid("record count has no record variable")
    }
    return (0L, 0L)
  }
  let base = record_vars[0].offset
  if base < fixed_end {
    raise Invalid("record region overlaps the header or fixed variables")
  }
  let mut step = 0L
  for variable in record_vars {
    if variable.offset != base + step {
      raise Invalid(
        "record variable offsets disagree with their interleaved layout",
      )
    }
    step += variable.padded_bytes
  }
  if record_vars.length() == 1 {
    // The NetCDF single-record-variable exception ignores padding between slabs.
    step = record_vars[0].slab_bytes
  }
  if records > 0L {
    let last = record_vars[record_vars.length() - 1]
    if base > source_bytes.to_int64() ||
      step > (source_bytes.to_int64() - base) / records {
      // A final multi-variable record can omit its final alignment bytes.
      let end = checked_product(records - 1L, step, source_bytes.to_int64())
      if last.offset > source_bytes.to_int64() ||
        end > source_bytes.to_int64() - last.offset ||
        last.slab_bytes > source_bytes.to_int64() - last.offset - end {
        raise Truncated("record region does not contain the declared records")
      }
    }
  }
  (base, step)
}

///|
pub fn open_bytes(
  source : Bytes,
  limits~ : Limits = default_limits(),
) -> Dataset raise CdfError {
  checked_limits(limits)
  if source.length() > limits.file_bytes {
    raise ResourceLimit("input exceeds file byte budget")
  }
  let input = Cursor::{ source, position: 0, }
  if input.take(3) != b"CDF" {
    raise Unsupported("expected NetCDF Classic CDF-1, CDF-2 or CDF-5")
  }
  let format = match input.uint(1) {
    1UL => Cdf1
    2UL => Cdf2
    5UL => Cdf5
    _ => raise Unsupported("unknown NetCDF Classic format version")
  }
  let raw_records = input.uint(if format == Cdf5 { 8 } else { 4 })
  let streaming = raw_records ==
    (if format == Cdf5 { 18446744073709551615UL } else { 4294967295UL })
  if !streaming && raw_records > 9223372036854775807UL {
    raise ResourceLimit("record count exceeds addressable range")
  }
  let initial_records = if streaming {
    0L
  } else {
    raw_records.reinterpret_as_int64()
  }
  let (dims, attrs, vars) = read_header(input, format, initial_records, limits)
  let (record_base, record_bytes) = validate_layout(
    vars,
    input.position,
    initial_records,
    source.length(),
  )
  let records = if streaming {
    if record_bytes == 0L || record_base > source.length().to_int64() {
      raise Invalid("streaming file has no complete record region")
    }
    let available = source.length().to_int64() - record_base
    if available % record_bytes != 0L {
      raise Truncated("streaming input ends in a partial record")
    }
    available / record_bytes
  } else {
    initial_records
  }
  if streaming {
    for index, dimension in dims {
      if dimension.unlimited {
        dims[index] = { ..dimension, length: records, }
      }
    }
    for index, variable in vars {
      if variable.record {
        vars[index] = {
          ..variable,
          shape: variable_shape(variable.dimensions, dims, limits),
        }
      }
    }
  }
  {
    format,
    records,
    streaming,
    header_bytes: input.position,
    record_bytes,
    source,
    dims,
    attrs,
    vars,
    limits,
  }
}

///|
pub fn Dataset::dimensions(self : Dataset) -> Array[Dimension] {
  self.dims.copy()
}

///|
pub fn Dataset::attributes(self : Dataset) -> Array[Attribute] {
  self.attrs.map(copy_attribute)
}

///|
pub fn Dataset::variables(self : Dataset) -> Array[VariableInfo] {
  self.vars.map(copy_info)
}

///|
fn Dataset::find(self : Dataset, name : String) -> VariableInfo raise CdfError {
  let canonical = checked_name(name, self.limits)
  for variable in self.vars {
    if variable.name == canonical {
      return variable
    }
  }
  raise Invalid("variable was not found: \{name}")
}

///|
pub fn Dataset::variable(
  self : Dataset,
  name : String,
) -> VariableInfo raise CdfError {
  copy_info(self.find(name))
}

///|
fn Dataset::value_at(
  self : Dataset,
  variable : VariableInfo,
  flat_index : Int64,
) -> Value raise CdfError {
  let width = variable.data_type.width().to_int64()
  let offset = if variable.record {
    let slab_values = variable.slab_bytes / width
    variable.offset +
    flat_index / slab_values * self.record_bytes +
    flat_index % slab_values * width
  } else {
    variable.offset + flat_index * width
  }
  if offset < 0L || offset > self.source.length().to_int64() - width {
    raise Truncated("requested value is outside the complete input")
  }
  Cursor::{ source: self.source, position: offset.to_int(), }.value(
    variable.data_type,
  )
}

///|
pub fn Dataset::values(
  self : Dataset,
  name : String,
) -> Array[Value] raise CdfError {
  let variable = self.find(name)
  let count = shape_count(variable.shape, self.limits.result_values.to_int64())
  Array::makei(count.to_int(), index => {
    self.value_at(variable, index.to_int64())
  })
}

///|
pub fn Dataset::document(self : Dataset) -> Document raise CdfError {
  let mut total = 0L
  let variables : Array[Variable] = []
  for variable in self.vars {
    let count = shape_count(
      variable.shape,
      self.limits.result_values.to_int64(),
    )
    if count > self.limits.result_values.to_int64() - total {
      raise ResourceLimit(
        "materialized document exceeds aggregate value budget",
      )
    }
    total += count
    variables.push({
      name: variable.name,
      data_type: variable.data_type,
      dimensions: variable.dimensions.copy(),
      attributes: variable.attributes.map(copy_attribute),
      values: self.values(variable.name),
    })
  }
  {
    format: self.format,
    dimensions: self.dimensions(),
    attributes: self.attributes(),
    variables,
  }
}