///|
/// The positional arguments of a method, in the order of its parameters. A
/// call with another number of arguments raises `LengthMismatch` at the path
/// `arguments` with the number of parameters and the number of arguments.
pub struct Arguments[A] {
  priv count : Int32
  priv encoder : (A) -> Array[HubValue] raise CodecError
  priv decoder : (ReadOnlyArray[HubValue]) -> A raise CodecError
}

///|
/// The path of the arguments in decode errors.
fn arguments_path() -> Path {
  Path::named("arguments")
}

///|
fn check_count(
  values : ReadOnlyArray[HubValue],
  count : Int32,
) -> Unit raise CodecError {
  guard values.length() == count else {
    raise LengthMismatch(
      path=arguments_path(),
      expected=count,
      found=values.length(),
    )
  }
}

///|
/// The number of parameters.
pub fn[A] Arguments::count(self : Arguments[A]) -> Int32 {
  self.count
}

///|
/// Encode the arguments.
pub fn[A] Arguments::encode(
  self : Arguments[A],
  value : A,
) -> Array[HubValue] raise CodecError {
  (self.encoder)(value)
}

///|
/// Decode the arguments. Errors have paths that start with `arguments`.
pub fn[A] Arguments::decode(
  self : Arguments[A],
  values : ReadOnlyArray[HubValue],
) -> A raise CodecError {
  (self.decoder)(values)
}

///|
/// No parameters.
pub fn args0() -> Arguments[Unit] {
  { count: 0, encoder: _ => [], decoder: values => check_count(values, 0), }
}

///|
/// One parameter.
pub fn[A] args1(a : Codec[A]) -> Arguments[A] {
  {
    count: 1,
    encoder: value => [(a.encoder)(value, arguments_path().index(0))],
    decoder: values => {
      check_count(values, 1)
      (a.decoder)(values[0], arguments_path().index(0))
    },
  }
}

///|
/// Build positional arguments from a tuple codec of `count` items.
fn[A] of_tuple(codec : Codec[A], count : Int32) -> Arguments[A] {
  {
    count,
    encoder: value => {
      guard (codec.encoder)(value, arguments_path()) is Array(items) else {
        return []
      }
      items.iter().collect()
    },
    decoder: values => {
      check_count(values, count)
      (codec.decoder)(Array(values), arguments_path())
    },
  }
}

///|
/// Two parameters.
pub fn[A, B] args2(a : Codec[A], b : Codec[B]) -> Arguments[(A, B)] {
  of_tuple(tuple2(a, b), 2)
}

///|
/// Three parameters.
pub fn[A, B, C] args3(
  a : Codec[A],
  b : Codec[B],
  c : Codec[C],
) -> Arguments[(A, B, C)] {
  of_tuple(tuple3(a, b, c), 3)
}

///|
/// Four parameters.
pub fn[A, B, C, D] args4(
  a : Codec[A],
  b : Codec[B],
  c : Codec[C],
  d : Codec[D],
) -> Arguments[(A, B, C, D)] {
  of_tuple(tuple4(a, b, c, d), 4)
}