///|
/// The integer type behind an enumeration: its width and signedness (F50, 2F45).
#derive(Eq, Hash, Debug)
pub(all) enum EnumBacking {
  SByte
  Byte
  Int16
  UInt16
  Int32
  UInt32
  Int64
  UInt64
}

///|
fn EnumBacking::kind(self : EnumBacking, label : String) -> IntegerKind {
  let (bits, signed) = match self {
    SByte => (8, true)
    Byte => (8, false)
    Int16 => (16, true)
    UInt16 => (16, false)
    Int32 => (32, true)
    UInt32 => (32, false)
    Int64 => (64, true)
    UInt64 => (64, false)
  }
  { label, bits, signed, }
}

///|
/// Whether the registered value `value` is in the range of the backing type. An `UInt64` value above
/// the `Int64` range is registered as its two's complement, so every `Int64` is in range for it.
fn EnumBacking::contains(self : EnumBacking, value : Int64) -> Bool {
  match self {
    SByte => value >= -128L && value <= 127L
    Byte => value >= 0L && value <= 255L
    Int16 => value >= -32768L && value <= 32767L
    UInt16 => value >= 0L && value <= 65535L
    Int32 => value >= -2147483648L && value <= 2147483647L
    UInt32 => value >= 0L && value <= 4294967295L
    Int64 | UInt64 => true
  }
}

///|
/// An enumeration value: the type and the value as 64-bit two's complement bits, sign-extended for
/// a signed backing type. Values of one type are equal when their bits are.
#derive(Eq, Hash, Debug)
pub(all) struct XamlEnumValue {
  type_name : @nodes.XamlTypeName
  bits : UInt64
}

///|
let enum_key : @nodes.ObjectKey[XamlEnumValue] = value_key()

///|
/// An enumeration value as a XAML value: a handle of the enumeration type that compares by value.
pub fn enum_value(value : XamlEnumValue) -> @nodes.XamlValue {
  Object(enum_key.wrap(value.type_name, value))
}

///|
/// The enumeration value in a value that `enum_value` made.
pub fn as_enum_value(value : @nodes.XamlValue) -> XamlEnumValue? {
  match value {
    Object(handle) => enum_key.unwrap(handle)
    _ => None
  }
}

///|
/// The registration of an enumeration type: its backing type, its named values and whether it is a
/// flags enumeration.
pub struct XamlEnumeration {
  backing : EnumBacking
  flags : Bool
  /// The named values in registration order, as 64-bit two's complement bits.
  values : ReadOnlyArray[(String, UInt64)]
}

///|
/// The value of the name `name`, compared case-sensitively.
pub fn XamlEnumeration::value_of(
  self : XamlEnumeration,
  name : String,
) -> UInt64? {
  self.values
  .iter()
  .filter(entry => entry.0 == name)
  .map(entry => entry.1)
  .head()
}

///|
/// The value that `text` stands for in the enumeration named `label` (F50, 2F45, Owner
/// 2026-12-01): trimmed text that starts with a digit or a sign is one in-range decimal integer;
/// otherwise it is a comma-separated list of case-sensitive names, each trimmed, combined with
/// bitwise OR. A number inside a list is not a name, so it is an error.
pub fn XamlEnumeration::parse(
  self : XamlEnumeration,
  label : String,
  text : String,
) -> UInt64 raise ValueError {
  let trimmed = dotnet_trim(text)
  if trimmed.is_empty() {
    raise ValueError("\"\{text}\" is not a value of \{label}")
  }
  let first = trimmed.code_unit_at(0)
  if is_ascii_digit(first) || first == '+' || first == '-' {
    return parse_decimal_integer(trimmed, self.backing.kind(label))
  }
  let mut result = 0UL
  for entry in trimmed[:].split(",") {
    let name = dotnet_trim(entry.to_owned())
    guard self.value_of(name) is Some(bits) else {
      raise ValueError(
        "\"\{text}\" is not a value of \{label}: \"\{name}\" is not one of its names",
      )
    }
    result = result | bits
  }
  result
}

///|
/// The value `bits` as a number of the backing type.
fn XamlEnumeration::number_text(
  self : XamlEnumeration,
  bits : UInt64,
) -> String {
  if self.backing.kind("").signed {
    bits.reinterpret_as_int64().to_string()
  } else {
    bits.to_string()
  }
}

///|
/// The text of `bits`, as .NET `Enum.Format` writes it: the name of a defined value, the names of a
/// flags combination in ascending value order joined with `", "`, and the number of an unnamed flags
/// value. An unnamed value of a non-flags enumeration is an error (Owner, 2026-12-01).
pub fn XamlEnumeration::format(
  self : XamlEnumeration,
  label : String,
  bits : UInt64,
) -> String raise ValueError {
  if self.values.iter().filter(entry => entry.1 == bits).head() is Some(entry) {
    return entry.0
  }
  if !self.flags {
    raise ValueError(
      "\{self.number_text(bits)} is not a named value of the enumeration \{label}",
    )
  }
  if bits == 0UL {
    return "0"
  }
  // Greedy from the largest value down, as `Enum.Format` takes flags.
  let sorted = self.values.iter().filter(entry => entry.1 != 0UL).collect()
  sorted.sort_by((a, b) => a.1.compare(b.1))
  let names = []
  let mut rest = bits
  for i = sorted.length() - 1; i >= 0; i = i - 1 {
    let (name, value) = sorted[i]
    if (rest & value) == value && rest != 0UL {
      rest = rest - value
      names.push(name)
    }
  }
  if rest != 0UL {
    return self.number_text(bits)
  }
  names.rev_in_place()
  names.join(", ")
}

///|
/// The converter of an enumeration type without a converter of its own.
fn enumeration_converter(
  type_name : @nodes.XamlTypeName,
  enumeration : XamlEnumeration,
) -> TypeConverter {
  let label = type_name.to_string()
  TypeConverter::from_text(
    (_, text) => {
      enum_value({ type_name, bits: enumeration.parse(label, text), })
    },
    format=(_, value) => {
      guard as_enum_value(value) is Some(v) else {
        raise ValueError("the value is not a value of the enumeration \{label}")
      }
      enumeration.format(label, v.bits)
    },
  )
}