///|
pub struct Histogram {
  edges : Array[Double]
  counts : Array[Int64]
  underflow : Int64
  overflow : Int64
  missing : Int64
  samples : Int64
}

///|
priv struct HistogramBuilder {
  edges : Array[Double]
  counts : Array[Int64]
  mut underflow : Int64
  mut overflow : Int64
  mut missing : Int64
  mut samples : Int64
}

///|
fn histogram_builder(edges : Array[Double]) -> HistogramBuilder raise CdfError {
  if edges.length() < 2 || edges.length() > 4097 {
    raise ResourceLimit("histogram requires two through 4097 explicit edges")
  }
  for index, edge in edges {
    if edge.is_nan() || edge.is_inf() || (index > 0 && edge <= edges[index - 1]) {
      raise Invalid("histogram edges must be finite and strictly increasing")
    }
  }
  {
    edges: edges.copy(),
    counts: Array::make(edges.length() - 1, 0L),
    underflow: 0L,
    overflow: 0L,
    missing: 0L,
    samples: 0L,
  }
}

///|
fn HistogramBuilder::observe(
  self : HistogramBuilder,
  optional : Double?,
) -> Unit raise CdfError {
  self.samples += 1L
  guard optional is Some(number) else {
    self.missing += 1L
    return
  }
  if number.is_nan() || number.is_inf() {
    raise Invalid("histogram expects finite numbers or explicit missing values")
  }
  let last = self.edges.length() - 1
  if number < self.edges[0] {
    self.underflow += 1L
    return
  }
  if number > self.edges[last] {
    self.overflow += 1L
    return
  }
  if number == self.edges[last] {
    self.counts[last - 1] += 1L
    return
  }
  let mut left = 0
  let mut right = last
  while left + 1 < right {
    let middle = left + (right - left) / 2
    if self.edges[middle] <= number {
      left = middle
    } else {
      right = middle
    }
  }
  self.counts[left] += 1L
}

///|
fn HistogramBuilder::finish(self : HistogramBuilder) -> Histogram {
  {
    edges: self.edges.copy(),
    counts: self.counts.copy(),
    underflow: self.underflow,
    overflow: self.overflow,
    missing: self.missing,
    samples: self.samples,
  }
}

///|
/// Bins are [left,right), except the final bin includes its right edge.
/// Values outside the edges are counted separately, never clamped to an end bin.
pub fn histogram_values(
  values : Array[Double?],
  edges : Array[Double],
) -> Histogram raise CdfError {
  if values.length() > 1000000 {
    raise ResourceLimit("histogram input exceeds value budget")
  }
  let result = histogram_builder(edges)
  for value in values {
    result.observe(value)
  }
  result.finish()
}

///|
/// Scan physical values through bounded tiles. Edges use the variable's own
/// physical units. This does not infer a distribution model or convert units.
pub fn Dataset::histogram(
  self : Dataset,
  name : String,
  edges : Array[Double],
  tile_values~ : Int32 = 65536,
) -> Histogram raise CdfError {
  if tile_values < 1 || tile_values > self.limits.result_values {
    raise Invalid("tile_values must be within the configured result budget")
  }
  let variable = self.find(name)
  let result = histogram_builder(edges)
  let model = packing(variable.data_type, variable.attributes)
  let tile_shape = Array::make(variable.shape.length(), 1L)
  let mut available = tile_values.to_int64()
  for axis = tile_shape.length() - 1; axis >= 0; axis = axis - 1 {
    let extent = if variable.shape[axis] == 0L {
      1L
    } else {
      variable.shape[axis]
    }
    let chosen = if available < extent { available } else { extent }
    tile_shape[axis] = chosen
    available /= chosen
  }
  self.for_each_tile(name, tile_shape, (_origin, block) => {
    for value in decode_with_packing(block, model).values {
      result.observe(value)
    }
  })
  result.finish()
}