///|
pub(all) suberror CdfError {
  Invalid(String)
  Truncated(String)
  Unsupported(String)
  ResourceLimit(String)
} derive(Debug)

///|
pub(all) enum Format {
  Cdf1
  Cdf2
  Cdf5
} derive(Eq, Debug)

///|
pub(all) enum DataType {
  Int8
  Char8
  Int16
  Int32
  Float32
  Float64
  UInt8
  UInt16
  UInt32
  Int64
  UInt64
} derive(Eq, Debug)

///|
pub(all) enum Value {
  Signed(Int64)
  Unsigned(UInt64)
  Real(Double)
  Character(Byte)
} derive(Eq, Debug)

///|
pub(all) struct Attribute {
  name : String
  data_type : DataType
  values : Array[Value]
} derive(Debug)

///|
pub(all) struct Dimension {
  name : String
  length : Int64
  unlimited : Bool
} derive(Eq, Debug)

///|
pub(all) struct Variable {
  name : String
  data_type : DataType
  dimensions : Array[Int32]
  attributes : Array[Attribute]
  values : Array[Value]
} derive(Debug)

///|
pub(all) struct Document {
  format : Format
  dimensions : Array[Dimension]
  attributes : Array[Attribute]
  variables : Array[Variable]
} derive(Debug)

///|
pub(all) struct Limits {
  file_bytes : Int32
  header_items : Int32
  result_values : Int32
  rank : Int32
  name_bytes : Int32
} derive(Debug)

///|
pub fn default_limits() -> Limits {
  {
    file_bytes: 67108864,
    header_items: 4096,
    result_values: 1000000,
    rank: 16,
    name_bytes: 256,
  }
}

///|
fn checked_limits(limits : Limits) -> Unit raise CdfError {
  let hard = default_limits()
  if limits.file_bytes < 32 ||
    limits.file_bytes > hard.file_bytes ||
    limits.header_items < 1 ||
    limits.header_items > hard.header_items ||
    limits.result_values < 1 ||
    limits.result_values > hard.result_values ||
    limits.rank < 1 ||
    limits.rank > hard.rank ||
    limits.name_bytes < 1 ||
    limits.name_bytes > hard.name_bytes {
    raise ResourceLimit(
      "limits must be positive and within documented hard bounds",
    )
  }
}

///|
pub fn DataType::width(self : DataType) -> Int32 {
  match self {
    Int8 | Char8 | UInt8 => 1
    Int16 | UInt16 => 2
    Int32 | UInt32 | Float32 => 4
    Int64 | UInt64 | Float64 => 8
  }
}

///|
fn DataType::tag(self : DataType) -> Int32 {
  match self {
    Int8 => 1
    Char8 => 2
    Int16 => 3
    Int32 => 4
    Float32 => 5
    Float64 => 6
    UInt8 => 7
    UInt16 => 8
    UInt32 => 9
    Int64 => 10
    UInt64 => 11
  }
}

///|
fn data_type(tag : Int32, format : Format) -> DataType raise CdfError {
  if format != Cdf5 && tag > 6 {
    raise Unsupported("extended integer types require CDF-5")
  }
  match tag {
    1 => Int8
    2 => Char8
    3 => Int16
    4 => Int32
    5 => Float32
    6 => Float64
    7 => UInt8
    8 => UInt16
    9 => UInt32
    10 => Int64
    11 => UInt64
    _ => raise Invalid("unrecognized NetCDF type tag")
  }
}

///|
pub fn DataType::fill_value(self : DataType) -> Value {
  match self {
    Int8 => Signed(-127L)
    Char8 => Character(0)
    Int16 => Signed(-32767L)
    Int32 => Signed(-2147483647L)
    Float32 | Float64 => Real(9.969209968386869e36)
    UInt8 => Unsigned(255UL)
    UInt16 => Unsigned(65535UL)
    UInt32 => Unsigned(4294967295UL)
    Int64 => Signed(-9223372036854775806L)
    UInt64 => Unsigned(18446744073709551614UL)
  }
}

///|
pub fn text_attribute(name : String, value : String) -> Attribute {
  {
    name,
    data_type: Char8,
    values: @utf8.encode(value).to_array().map(fn(byte) { Character(byte) }),
  }
}

///|
fn checked_name(name : String, limits : Limits) -> String raise CdfError {
  let canonical = @normalization.nfc(name)
  let bytes = @utf8.encode(canonical)
  if bytes.is_empty() ||
    bytes.length() > limits.name_bytes ||
    canonical.has_suffix(" ") {
    raise Invalid("invalid empty, long or trailing-space name")
  }
  for index, character in canonical.to_array() {
    let code = character.to_int()
    if code <= 31 || code == 127 || character == '/' {
      raise Invalid("names cannot contain control characters or slash")
    }
    if index == 0 &&
      code < 128 &&
      character != '_' &&
      !(character >= 'a' && character <= 'z') &&
      !(character >= 'A' && character <= 'Z') &&
      !(character >= '0' && character <= '9') {
      raise Invalid(
        "name must begin with a letter, digit, underscore or Unicode",
      )
    }
  }
  canonical
}

///|
fn checked_product(a : Int64, b : Int64, limit : Int64) -> Int64 raise CdfError {
  if a < 0L || b < 0L || (a != 0L && b > limit / a) {
    raise ResourceLimit("shape or byte product exceeds the configured budget")
  }
  a * b
}

///|
fn padded4(size : Int64) -> Int64 raise CdfError {
  if size < 0L || size > 9223372036854775804L {
    raise Invalid("invalid size for four-byte alignment")
  }
  (size + 3L) / 4L * 4L
}