///|
/// `None` as null and `Some(value)` as the value. A value that encodes as null,
/// such as the `None` of a nested option, raises `NullInOption`, because a decode
/// could not tell it from `None`. A missing record property
/// decodes to `None`.
pub fn[T] option(codec : Codec[T]) -> Codec[T?] {
  {
    encoder: (value, path) => {
      match value {
        None => Null
        Some(inner) => {
          let encoded = (codec.encoder)(inner, path)
          guard !(encoded is Null) else { raise NullInOption(path~) }
          encoded
        }
      }
    },
    decoder: (value, path) => {
      match value {
        Null => None
        _ => Some((codec.decoder)(value, path))
      }
    },
    absent: Some(None),
    no_result: false,
  }
}

///|
/// An array with items of one type.
pub fn[T] array(codec : Codec[T]) -> Codec[Array[T]] {
  Codec::new(
    encode=(values, path) => {
      let items = []
      for i, value in values {
        items.push((codec.encoder)(value, path.index(i)))
      }
      HubValue::array(items)
    },
    decode=(value, path) => {
      guard value is Array(items) else { raise mismatch(path, Array, value) }
      let values = []
      for i, item in items {
        values.push((codec.decoder)(item, path.index(i)))
      }
      values
    },
  )
}

///|
/// The items of an array value with exactly `count` items.
fn items_of(
  value : HubValue,
  count : Int32,
  path : Path,
) -> ReadOnlyArray[HubValue] raise CodecError {
  guard value is Array(items) else { raise mismatch(path, Array, value) }
  guard items.length() == count else {
    raise LengthMismatch(path~, expected=count, found=items.length())
  }
  items
}

///|
/// Two values as an array of two items, in order. Use it for the arguments of a
/// method with two parameters: a different number of arguments raises
/// `LengthMismatch` with both numbers.
pub fn[A, B] tuple2(a : Codec[A], b : Codec[B]) -> Codec[(A, B)] {
  Codec::new(
    encode=(value, path) => {
      HubValue::array([
        (a.encoder)(value.0, path.index(0)),
        (b.encoder)(value.1, path.index(1)),
      ])
    },
    decode=(value, path) => {
      let items = items_of(value, 2, path)
      (
        (a.decoder)(items[0], path.index(0)),
        (b.decoder)(items[1], path.index(1)),
      )
    },
  )
}

///|
/// Three values as an array of three items, in order.
pub fn[A, B, C] tuple3(
  a : Codec[A],
  b : Codec[B],
  c : Codec[C],
) -> Codec[(A, B, C)] {
  Codec::new(
    encode=(value, path) => {
      HubValue::array([
        (a.encoder)(value.0, path.index(0)),
        (b.encoder)(value.1, path.index(1)),
        (c.encoder)(value.2, path.index(2)),
      ])
    },
    decode=(value, path) => {
      let items = items_of(value, 3, path)
      (
        (a.decoder)(items[0], path.index(0)),
        (b.decoder)(items[1], path.index(1)),
        (c.decoder)(items[2], path.index(2)),
      )
    },
  )
}

///|
/// Four values as an array of four items, in order.
pub fn[A, B, C, D] tuple4(
  a : Codec[A],
  b : Codec[B],
  c : Codec[C],
  d : Codec[D],
) -> Codec[(A, B, C, D)] {
  Codec::new(
    encode=(value, path) => {
      HubValue::array([
        (a.encoder)(value.0, path.index(0)),
        (b.encoder)(value.1, path.index(1)),
        (c.encoder)(value.2, path.index(2)),
        (d.encoder)(value.3, path.index(3)),
      ])
    },
    decode=(value, path) => {
      let items = items_of(value, 4, path)
      (
        (a.decoder)(items[0], path.index(0)),
        (b.decoder)(items[1], path.index(1)),
        (c.decoder)(items[2], path.index(2)),
        (d.decoder)(items[3], path.index(3)),
      )
    },
  )
}

///|
/// Two different cases of an enum have the same wire value, so a decode could
/// not give back the encoded case.
#derive(Eq, Debug)
pub suberror EnumMappingError {
  /// The wire value `value` belongs to two different cases.
  AmbiguousValue(value~ : String)
}

///|
pub extend EnumMappingError with Eq::{equal, not_equal}

///|
pub extend EnumMappingError with @debug.Debug::{to_repr}

///|
/// Text for people that describes the fault.
pub fn EnumMappingError::message(self : EnumMappingError) -> String {
  let AmbiguousValue(value~) = self
  "The wire value \{value} belongs to two different cases of the enum"
}

///|
/// The wire value of each case of an enum. Each wire value belongs to one case,
/// so each case comes back from a round trip.
pub struct EnumMapping[T, W] {
  priv cases : ReadOnlyArray[(T, W)]
}

///|
/// The mapping of `cases`. A case can have more than one wire value: encode uses
/// the first one, and decode reads each. A wire value of two different cases
/// raises `AmbiguousValue`.
pub fn[T : Eq, W : Eq + Show] EnumMapping::new(
  cases : ArrayView[(T, W)],
) -> EnumMapping[T, W] raise EnumMappingError {
  for i, entry in cases {
    for j in 0.. W raise CodecError {
  for entry in self.cases {
    if entry.0 == case {
      return entry.1
    }
  }
  raise UnknownEnumValue(path~, value=Show::to_string(case))
}

///|
/// An enum as the number of its position in `cases`: the first case is 0, the
/// second case is 1. This is the default of System.Text.Json for a .NET enum
/// with no explicit values.
pub fn[T : Eq + Show] enumeration(cases : Array[T]) -> Codec[T] {
  // Each position is a different number, so the mapping is not ambiguous.
  enum_numbers({
    cases: ReadOnlyArray::from_array(cases.mapi((i, case) => (case, i))),
  })
}

///|
/// An enum as the number that `mapping` gives for each case. Use it when the .NET
/// enum has explicit values.
pub fn[T : Eq + Show] enum_numbers(mapping : EnumMapping[T, Int32]) -> Codec[T] {
  Codec::new(
    encode=(value, path) => Int(mapping.wire(value, path).to_int64()),
    decode=(value, path) => {
      let number = whole_in_range(
        whole_of(value, path),
        -2147483648L,
        2147483647L,
        path,
      ).to_int()
      for entry in mapping.cases {
        if entry.1 == number {
          return entry.0
        }
      }
      raise UnknownEnumValue(path~, value=number.to_string())
    },
  )
}

///|
/// An enum as the text that `mapping` gives for each case. This is an explicit
/// choice, as `JsonStringEnumConverter` is in .NET. Decode looks for an equal
/// text first, and then matches with no regard to the case of ASCII letters.
pub fn[T : Eq + Show] enum_names(mapping : EnumMapping[T, String]) -> Codec[T] {
  Codec::new(encode=(value, path) => String(mapping.wire(value, path)), decode=(
    value,
    path,
  ) => {
    guard value is String(text) else { raise mismatch(path, String, value) }
    for entry in mapping.cases {
      if entry.1 == text {
        return entry.0
      }
    }
    let lower = text.to_lower()
    for entry in mapping.cases {
      if entry.1.to_lower() == lower {
        return entry.0
      }
    }
    raise UnknownEnumValue(path~, value=text.escape())
  })
}

///|
/// Lower the uppercase ASCII letters at the start of `name`, as the camelCase
/// policy of System.Text.Json does. The last letter of a run stays when it starts
/// the next word: `URLValue` gives `urlValue`.
fn lower_first_word(name : String) -> String {
  let chars = name.to_array()
  for i, char in chars {
    guard char.is_ascii_uppercase() else { break }
    let starts_word = i > 0 &&
      i + 1 < chars.length() &&
      !chars[i + 1].is_ascii_uppercase()
    guard !starts_word else { break }
    chars[i] = char.to_ascii_lowercase()
  }
  String::from_array(chars)
}

///|
/// The camelCase form of a field name. A snake_case name joins its words:
/// `user_name` gives `userName`. Another name gets the camelCase policy of
/// System.Text.Json: `UserName` gives `userName`, and `URLValue` gives
/// `urlValue`. Only ASCII letters change, because the MoonBit core library has no
/// Unicode case conversion; give the property name for a name that starts with
/// another letter.
pub fn camel_case(name : String) -> String {
  let parts = name
    .split("_")
    .filter(part => !part.is_empty())
    .map(part => part.to_owned())
    .collect()
  let out = StringBuilder()
  for i, part in parts {
    if i == 0 {
      out.write_string(lower_first_word(part))
    } else {
      for j, char in part.to_array() {
        out.write_char(if j == 0 { char.to_ascii_uppercase() } else { char })
      }
    }
  }
  out.to_string()
}

///|
/// A property of a record codec: the property name, the codec of the value and
/// the function that reads the value from the record.
pub struct Field[R, F] {
  priv property : String
  priv codec : Codec[F]
  priv get : (R) -> F
}

///|
/// A record property for the field `name`. The property name is the camelCase
/// form of `name`, the default of System.Text.Json Web. Give `property` to use
/// another property name; that is an explicit choice.
pub fn[R, F] field(
  name : String,
  codec : Codec[F],
  get : (R) -> F,
  property? : String,
) -> Field[R, F] {
  { property: property.unwrap_or(camel_case(name)), codec, get, }
}

///|
/// The property name.
pub fn[R, F] Field::property(self : Field[R, F]) -> String {
  self.property
}

///|
fn[R, F] Field::encode_into(
  self : Field[R, F],
  record : R,
  path : Path,
  entries : Array[(String, HubValue)],
) -> Unit raise CodecError {
  entries.push(
    (
      self.property,
      (self.codec.encoder)((self.get)(record), path.key(self.property)),
    ),
  )
}

///|
/// Decode the property from `map`. The name matches with no regard to case
/// when no name is equal, as System.Text.Json reads SignalR payloads.
fn[R, F] Field::decode_from(
  self : Field[R, F],
  map : HubMap,
  path : Path,
) -> F raise CodecError {
  match map.get_ignore_case(self.property) {
    Some(value) => (self.codec.decoder)(value, path.key(self.property))
    None =>
      match self.codec.absent {
        Some(value) => value
        None => raise MissingProperty(path~, name=self.property)
      }
  }
}

///|
/// Build the object value from `entries`.
fn object_of(
  entries : Array[(String, HubValue)],
  path : Path,
) -> HubValue raise CodecError {
  Map(HubMap::new(entries) catch { cause => raise Rejected(path~, cause~) })
}

///|
/// The map of an object value.
fn map_of(value : HubValue, path : Path) -> HubMap raise CodecError {
  guard value is Map(map) else { raise mismatch(path, Map, value) }
  map
}

///|
/// Run `make`, the constructor of a record. Its error becomes `Rejected`.
fn[R] made(make : () -> R raise, path : Path) -> R raise CodecError {
  make() catch {
    cause => raise Rejected(path~, cause~)
  }
}

///|
/// A record with one field as an object. Decode ignores properties that it
/// does not know.
pub fn[R, A] record1(make : (A) -> R raise?, a : Field[R, A]) -> Codec[R] {
  Codec::new(
    encode=(value, path) => {
      let entries = []
      a.encode_into(value, path, entries)
      object_of(entries, path)
    },
    decode=(value, path) => {
      let map = map_of(value, path)
      let va = a.decode_from(map, path)
      made(() => make(va), path)
    },
  )
}

///|
/// A record with two fields as an object.
pub fn[R, A, B] record2(
  make : (A, B) -> R raise?,
  a : Field[R, A],
  b : Field[R, B],
) -> Codec[R] {
  Codec::new(
    encode=(value, path) => {
      let entries = []
      a.encode_into(value, path, entries)
      b.encode_into(value, path, entries)
      object_of(entries, path)
    },
    decode=(value, path) => {
      let map = map_of(value, path)
      let va = a.decode_from(map, path)
      let vb = b.decode_from(map, path)
      made(() => make(va, vb), path)
    },
  )
}

///|
/// A record with three fields as an object.
pub fn[R, A, B, C] record3(
  make : (A, B, C) -> R raise?,
  a : Field[R, A],
  b : Field[R, B],
  c : Field[R, C],
) -> Codec[R] {
  Codec::new(
    encode=(value, path) => {
      let entries = []
      a.encode_into(value, path, entries)
      b.encode_into(value, path, entries)
      c.encode_into(value, path, entries)
      object_of(entries, path)
    },
    decode=(value, path) => {
      let map = map_of(value, path)
      let va = a.decode_from(map, path)
      let vb = b.decode_from(map, path)
      let vc = c.decode_from(map, path)
      made(() => make(va, vb, vc), path)
    },
  )
}

///|
/// A record with four fields as an object.
pub fn[R, A, B, C, D] record4(
  make : (A, B, C, D) -> R raise?,
  a : Field[R, A],
  b : Field[R, B],
  c : Field[R, C],
  d : Field[R, D],
) -> Codec[R] {
  Codec::new(
    encode=(value, path) => {
      let entries = []
      a.encode_into(value, path, entries)
      b.encode_into(value, path, entries)
      c.encode_into(value, path, entries)
      d.encode_into(value, path, entries)
      object_of(entries, path)
    },
    decode=(value, path) => {
      let map = map_of(value, path)
      let va = a.decode_from(map, path)
      let vb = b.decode_from(map, path)
      let vc = c.decode_from(map, path)
      let vd = d.decode_from(map, path)
      made(() => make(va, vb, vc, vd), path)
    },
  )
}

///|
/// A record with five fields as an object.
pub fn[R, A, B, C, D, E] record5(
  make : (A, B, C, D, E) -> R raise?,
  a : Field[R, A],
  b : Field[R, B],
  c : Field[R, C],
  d : Field[R, D],
  e : Field[R, E],
) -> Codec[R] {
  Codec::new(
    encode=(value, path) => {
      let entries = []
      a.encode_into(value, path, entries)
      b.encode_into(value, path, entries)
      c.encode_into(value, path, entries)
      d.encode_into(value, path, entries)
      e.encode_into(value, path, entries)
      object_of(entries, path)
    },
    decode=(value, path) => {
      let map = map_of(value, path)
      let va = a.decode_from(map, path)
      let vb = b.decode_from(map, path)
      let vc = c.decode_from(map, path)
      let vd = d.decode_from(map, path)
      let ve = e.decode_from(map, path)
      made(() => make(va, vb, vc, vd, ve), path)
    },
  )
}

///|
/// A record with six fields as an object.
pub fn[R, A, B, C, D, E, F] record6(
  make : (A, B, C, D, E, F) -> R raise?,
  a : Field[R, A],
  b : Field[R, B],
  c : Field[R, C],
  d : Field[R, D],
  e : Field[R, E],
  f : Field[R, F],
) -> Codec[R] {
  Codec::new(
    encode=(value, path) => {
      let entries = []
      a.encode_into(value, path, entries)
      b.encode_into(value, path, entries)
      c.encode_into(value, path, entries)
      d.encode_into(value, path, entries)
      e.encode_into(value, path, entries)
      f.encode_into(value, path, entries)
      object_of(entries, path)
    },
    decode=(value, path) => {
      let map = map_of(value, path)
      let va = a.decode_from(map, path)
      let vb = b.decode_from(map, path)
      let vc = c.decode_from(map, path)
      let vd = d.decode_from(map, path)
      let ve = e.decode_from(map, path)
      let vf = f.decode_from(map, path)
      made(() => make(va, vb, vc, vd, ve, vf), path)
    },
  )
}