///|
pub struct FlagData {
  shape : Array[Int64]
  meanings : Array[String]
  // A missing storage sample is None. A valid sample can match zero or several
  // meanings. Values are labels rather than floating-point bit representations.
  values : Array[Array[String]?]
}

///|
fn integral_type(kind : DataType) -> Bool {
  kind != Char8 && kind != Float32 && kind != Float64
}

///|
fn storage_bits(value : Value, kind : DataType) -> UInt64 raise CdfError {
  checked_value(value, kind)
  let mask = if kind.width() == 8 {
    18446744073709551615UL
  } else {
    (1UL << (8 * kind.width())) - 1UL
  }
  match value {
    Signed(number) => number.reinterpret_as_uint64() & mask
    Unsigned(number) => number
    _ => raise Invalid("quality flags require integral storage values")
  }
}

///|
fn flag_attribute(
  attributes : Array[Attribute],
  name : String,
  kind : DataType,
  count : Int32,
) -> Array[UInt64]? raise CdfError {
  match find_attribute(attributes, name) {
    None => None
    Some(attribute) => {
      if attribute.data_type != kind || attribute.values.length() != count {
        raise Invalid("flag attribute dtype and length must match its meanings")
      }
      Some(attribute.values.map(value => storage_bits(value, kind)))
    }
  }
}

///|
fn flag_less(left : Value, right : Value) -> Bool raise CdfError {
  match (left, right) {
    (Signed(a), Signed(b)) => a < b
    (Unsigned(a), Unsigned(b)) => a < b
    _ => raise Invalid("flag validity bounds must have the same integral type")
  }
}

///|
fn flag_bounds(
  attributes : Array[Attribute],
  kind : DataType,
) -> (Value?, Value?) raise CdfError {
  fn values(name : String, count : Int32) -> Array[Value]? raise CdfError {
    match find_attribute(attributes, name) {
      None => None
      Some(attribute) => {
        if attribute.data_type != kind || attribute.values.length() != count {
          raise Invalid(
            "flag validity metadata must match storage type and arity",
          )
        }
        for value in attribute.values {
          checked_value(value, kind)
        }
        Some(attribute.values)
      }
    }
  }
  if values("valid_range", 2) is Some(range) {
    return (Some(range[0]), Some(range[1]))
  }
  let minimum = match values("valid_min", 1) {
    None => None
    Some(v) => Some(v[0])
  }
  let maximum = match values("valid_max", 1) {
    None => None
    Some(v) => Some(v[0])
  }
  (minimum, maximum)
}

///|
/// CF 1.12 flags: equality-only enumerations, independent bit masks, and combined
/// masks/values. Bit tests preserve the full 64-bit integer, including the high bit.
/// Missing markers are checked before matching. Undeclared codes yield [].
pub fn decode_flags(
  block : DataBlock,
  attributes : Array[Attribute],
) -> FlagData raise CdfError {
  if !integral_type(block.data_type) ||
    block.shape.length() > 16 ||
    shape_count(block.shape, 1000000L) != block.values.length().to_int64() {
    raise Invalid("flags need an integral block with a valid bounded shape")
  }
  let meaning_attribute = match find_attribute(attributes, "flag_meanings") {
    None => raise Invalid("flags require flag_meanings")
    Some(attribute) => attribute
  }
  let meanings = words(attribute_text(meaning_attribute))
  if meanings.is_empty() || meanings.length() > 256 {
    raise ResourceLimit("flag meanings must contain one through 256 labels")
  }
  let seen : Map[String, Bool] = Map([])
  for meaning in meanings {
    if seen.contains(meaning) {
      raise Invalid("duplicate flag meaning")
    }
    seen[meaning] = true
    for character in meaning.to_array() {
      if !(character >= 'a' && character <= 'z') &&
        !(character >= 'A' && character <= 'Z') &&
        !(character >= '0' && character <= '9') &&
        character != '_' &&
        character != '-' &&
        character != '.' &&
        character != '+' &&
        character != '@' {
        raise Invalid("flag meaning uses characters outside CF label syntax")
      }
    }
  }
  let masks = flag_attribute(
    attributes,
    "flag_masks",
    block.data_type,
    meanings.length(),
  )
  let codes = flag_attribute(
    attributes,
    "flag_values",
    block.data_type,
    meanings.length(),
  )
  if masks is None && codes is None {
    raise Invalid("flags require flag_values, flag_masks, or both")
  }
  if masks is Some(masks) {
    for i, mask in masks {
      if mask == 0UL {
        raise Invalid("flag masks cannot be zero")
      }
      if codes is Some(codes) && (codes[i] & mask) != codes[i] {
        raise Invalid("flag value contains a bit outside its mask")
      }
    }
  } else if codes is Some(codes) {
    for i in 0.. false
    Some(attribute) => {
      let text = attribute_text(attribute)
      text == "true" || text == "True"
    }
  }
  let low = low.map(value => {
    unsigned_storage(value, block.data_type, unsigned_view)
  })
  let high = high.map(value => {
    unsigned_storage(value, block.data_type, unsigned_view)
  })
  if low is Some(a) && high is Some(b) && flag_less(b, a) {
    raise Invalid("flag validity minimum exceeds maximum")
  }
  for name in ["_FillValue", "missing_value"] {
    if find_attribute(attributes, name) is Some(attribute) {
      if attribute.data_type != block.data_type ||
        (name == "_FillValue" && attribute.values.length() != 1) {
        raise Invalid("flag missing markers must match storage type")
      }
      for value in attribute.values {
        checked_value(value, block.data_type)
        missing.push(value)
      }
    }
  }
  // Bound expanded label output, rather than only the number of raw samples.
  let mut expanded = 0
  let values = block.values.map(raw => {
    let bits = storage_bits(raw, block.data_type)
    if missing.any(value => same_value(value, raw)) {
      return None
    }
    let comparable = unsigned_storage(raw, block.data_type, unsigned_view)
    if (low is Some(bound) && flag_less(comparable, bound)) ||
      (high is Some(bound) && flag_less(bound, comparable)) {
      return None
    }
    let matched : Array[String] = []
    for index, meaning in meanings {
      let mask = match masks {
        None => 18446744073709551615UL
        Some(masks) => masks[index]
      }
      let active = match codes {
        Some(codes) => (bits & mask) == codes[index]
        None => (bits & mask) != 0UL
      }
      if active {
        expanded += 1
        if expanded > 1000000 {
          raise ResourceLimit("expanded flag labels exceed output budget")
        }
        matched.push(meaning)
      }
    }
    Some(matched)
  })
  { shape: block.shape.copy(), meanings, values, }
}

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