///|
pub struct PhysicalData {
  shape : Array[Int64]
  values : Array[Double?]
  missing : Int32
  outside_valid_range : Int32
  nonfinite : Int32
  scale_factor : Double
  add_offset : Double
}

///|
pub struct NumericSummary {
  count : Int32
  missing : Int32
  minimum : Double?
  maximum : Double?
  mean : Double?
  population_stddev : Double?
}

///|
priv struct Packing {
  kind : DataType
  unsigned_view : Bool
  scale : Double
  offset : Double
  missing : Array[Value]
  minimum : Double?
  maximum : Double?
}

///|
pub fn attribute_text(attribute : Attribute) -> String raise CdfError {
  if attribute.data_type != Char8 {
    raise Invalid("attribute does not contain character data")
  }
  let bytes = attribute.values.map(value => {
    match value {
      Character(byte) => byte
      _ => raise Invalid("invalid character attribute value")
    }
  })
  let mut end = bytes.length()
  // Older NetCDF writers sometimes include a C string terminator in NC_CHAR
  // attribute lengths. Raw attribute.values still retains every original byte.
  while end > 0 && bytes[end - 1] == 0 {
    end -= 1
  }
  @utf8.decode(Bytes::from_array(bytes[:end])[:]) catch {
    _ => raise Invalid("character attribute is not UTF-8 text")
  }
}

///|
/// Convert a raw numeric scalar without silently rounding 64-bit integers.
/// Read or write Value::Signed/Unsigned directly when exact wider values matter.
pub fn numeric_value(value : Value) -> Double raise CdfError {
  match value {
    Signed(number) => {
      if number < -9007199254740992L || number > 9007199254740992L {
        raise Unsupported("integer exceeds the exact Float64 conversion range")
      }
      number.to_double()
    }
    Unsigned(number) => {
      if number > 9007199254740992UL {
        raise Unsupported(
          "unsigned integer exceeds the exact Float64 conversion range",
        )
      }
      number.to_double()
    }
    Real(number) => number
    Character(_) =>
      raise Unsupported("character data requires a character interface")
  }
}

///|
fn find_attribute(attributes : Array[Attribute], name : String) -> Attribute? {
  attributes.iter().find_first(attribute => attribute.name == name)
}

///|
fn scalar_attribute(
  attributes : Array[Attribute],
  name : String,
  fallback : Double,
) -> Double raise CdfError {
  match find_attribute(attributes, name) {
    None => fallback
    Some(attribute) => {
      if attribute.values.length() != 1 {
        raise Invalid("\{name} must be scalar")
      }
      let value = numeric_value(attribute.values[0])
      if value.is_nan() || value.is_inf() {
        raise Invalid("\{name} must be finite")
      }
      value
    }
  }
}

///|
fn unsigned_storage(
  value : Value,
  kind : DataType,
  reinterpret : Bool,
) -> Value {
  if !reinterpret {
    return value
  }
  match value {
    Signed(number) => {
      let mask = if kind == Int64 {
        18446744073709551615UL
      } else {
        (1UL << (8 * kind.width())) - 1UL
      }
      Unsigned(number.reinterpret_as_uint64() & mask)
    }
    _ => value
  }
}

///|
fn packing(
  kind : DataType,
  attributes : Array[Attribute],
) -> Packing raise CdfError {
  if kind == Char8 {
    raise Unsupported("physical scaling is defined for numeric variables")
  }
  let limits = default_limits()
  let attributes = normalized_attributes(attributes, Cdf5, limits, HeaderBudget::{
    remaining: limits.header_items,
    value_remaining: limits.result_values,
  })
  let unsigned_view = match find_attribute(attributes, "_Unsigned") {
    None => false
    Some(attribute) => {
      let value = attribute_text(attribute)
      let requested = value == "true" || value == "True"
      requested &&
      (kind == Int8 || kind == Int16 || kind == Int32 || kind == Int64)
    }
  }
  let scale = scalar_attribute(attributes, "scale_factor", 1.0)
  let offset = scalar_attribute(attributes, "add_offset", 0.0)
  let fill = match find_attribute(attributes, "_FillValue") {
    None => kind.fill_value()
    Some(attribute) => {
      if attribute.data_type != kind || attribute.values.length() != 1 {
        raise Invalid("_FillValue must match the variable storage type")
      }
      attribute.values[0]
    }
  }
  let missing = [fill]
  if find_attribute(attributes, "missing_value") is Some(attribute) {
    if attribute.data_type != kind {
      raise Invalid("missing_value must match the variable storage type")
    }
    for value in attribute.values {
      missing.push(value)
    }
  }
  let bound = fn(attribute : Attribute, index : Int32) raise CdfError {
    if attribute.data_type != kind {
      raise Invalid("validity attributes must match the storage type")
    }
    let value = numeric_value(
      unsigned_storage(attribute.values[index], kind, unsigned_view),
    )
    if value.is_nan() || value.is_inf() {
      raise Invalid("validity bounds must be finite")
    }
    value
  }
  let mut minimum : Double? = None
  let mut maximum : Double? = None
  match find_attribute(attributes, "valid_range") {
    Some(attribute) => {
      if attribute.values.length() != 2 {
        raise Invalid("valid_range must contain exactly two values")
      }
      minimum = Some(bound(attribute, 0))
      maximum = Some(bound(attribute, 1))
    }
    None =>
      for name in ["valid_min", "valid_max"] {
        if find_attribute(attributes, name) is Some(attribute) {
          if attribute.values.length() != 1 {
            raise Invalid("valid_min and valid_max must be scalars")
          }
          let value = Some(bound(attribute, 0))
          if name == "valid_min" {
            minimum = value
          } else {
            maximum = value
          }
        }
      }
  }
  if minimum is Some(low) && maximum is Some(high) && low > high {
    raise Invalid("validity minimum exceeds maximum")
  }
  { kind, unsigned_view, scale, offset, missing, minimum, maximum, }
}

///|
fn out_of_range(value : Double, packing : Packing) -> Bool {
  (packing.minimum is Some(minimum) && value < minimum) ||
  (packing.maximum is Some(maximum) && value > maximum)
}

///|
pub fn decode_physical(
  block : DataBlock,
  attributes : Array[Attribute],
) -> PhysicalData raise CdfError {
  decode_with_packing(block, packing(block.data_type, attributes))
}

///|
// Scan operations compile the immutable metadata once and reuse it for each tile.
fn decode_with_packing(
  block : DataBlock,
  model : Packing,
) -> PhysicalData raise CdfError {
  if block.data_type != model.kind ||
    shape_count(block.shape, 1000000L) != block.values.length().to_int64() {
    raise Invalid("block shape and value count disagree")
  }
  let mut missing = 0
  let mut outside_valid_range = 0
  let mut nonfinite = 0
  let values = block.values.map(raw => {
    let raw = storage_value(raw, block.data_type)
    if model.missing.any(marker => same_value(marker, raw)) {
      missing += 1
      return None
    }
    let number = numeric_value(
      unsigned_storage(raw, model.kind, model.unsigned_view),
    )
    if number.is_nan() || number.is_inf() {
      nonfinite += 1
      return None
    }
    if out_of_range(number, model) {
      outside_valid_range += 1
      return None
    }
    let physical = number * model.scale + model.offset
    if physical.is_nan() || physical.is_inf() {
      raise Invalid("physical scale and offset overflow Float64")
    }
    Some(physical)
  })
  {
    shape: block.shape.copy(),
    values,
    missing,
    outside_valid_range,
    nonfinite,
    scale_factor: model.scale,
    add_offset: model.offset,
  }
}

///|
pub fn Dataset::physical_section(
  self : Dataset,
  name : String,
  start : Array[Int64],
  count : Array[Int64],
  stride~ : Array[Int64] = [],
) -> PhysicalData raise CdfError {
  let variable = self.find(name)
  decode_physical(
    self.section(name, start, count, stride~),
    variable.attributes,
  )
}

///|
fn rounded_even(value : Double) -> Double {
  let lower = @math.floor(value)
  let fraction = value - lower
  if fraction < 0.5 {
    lower
  } else if fraction > 0.5 {
    lower + 1.0
  } else if lower.to_int64() % 2L == 0L {
    lower
  } else {
    lower + 1.0
  }
}

///|
fn packed_scalar(value : Double, model : Packing) -> Value raise CdfError {
  if value.is_nan() || value.is_inf() {
    raise Invalid("physical input must be finite or explicitly missing")
  }
  let mut number = (value - model.offset) / model.scale
  if number.is_nan() || number.is_inf() {
    raise Invalid("packing arithmetic overflow")
  }
  if model.kind == Float32 {
    if number.abs() > 3.4028234663852886e38 {
      raise Invalid("packed value exceeds Float32")
    }
    number = Float::from_double(number).to_double()
  } else if model.kind != Float64 {
    if number.abs() > 9007199254740992.0 {
      raise Unsupported("integer packing exceeds the exact Float64 input range")
    }
    number = rounded_even(number)
  }
  if out_of_range(number, model) {
    raise Invalid("packed value is outside declared valid range")
  }
  let packed = match model.kind {
    Float32 | Float64 => Real(number)
    UInt8 | UInt16 | UInt32 | UInt64 => {
      if number < 0.0 {
        raise Invalid("negative value for unsigned storage")
      }
      Unsigned(number.to_int64().reinterpret_as_uint64())
    }
    Int8 | Int16 | Int32 | Int64 => {
      let integer = if model.unsigned_view {
        if number < 0.0 {
          raise Invalid("negative value for _Unsigned storage")
        }
        let width = 8 * model.kind.width()
        if width < 64 {
          let modulus = 1L << width
          let n = number.to_int64()
          if n >= modulus {
            raise Invalid("packed unsigned value exceeds storage range")
          }
          if n >= modulus / 2L {
            n - modulus
          } else {
            n
          }
        } else {
          number.to_int64()
        }
      } else {
        number.to_int64()
      }
      Signed(integer)
    }
    Char8 => raise Unsupported("cannot pack numeric values as characters")
  }
  checked_value(packed, model.kind)
  if model.missing.any(marker => same_value(marker, packed)) {
    raise Invalid("rounded numeric value collides with a missing-value marker")
  }
  packed
}

///|
/// Pack finite physical values with explicit scale/offset and ties-to-even
/// rounding. None uses the declared/default fill value. The whole result is
/// validated before the caller receives any packed values.
pub fn pack_physical(
  values : Array[Double?],
  kind : DataType,
  attributes : Array[Attribute],
) -> Array[Value] raise CdfError {
  if values.length() > 1000000 {
    raise ResourceLimit("physical value count exceeds budget")
  }
  let model = packing(kind, attributes)
  if model.scale == 0.0 {
    raise Invalid("packing requires a nonzero scale_factor")
  }
  values.map(value => {
    match value {
      None => model.missing[0]
      Some(number) => packed_scalar(number, model)
    }
  })
}

///|
pub fn summarize(values : Array[Double?]) -> NumericSummary raise CdfError {
  if values.length() > 1000000 {
    raise ResourceLimit("summary input exceeds value budget")
  }
  let state = summary_state()
  for value in values {
    state.observe(value)
  }
  state.finish()
}