///|
/// A text form that a codec reads.
#derive(Eq, Debug)
pub(all) enum TextFormat {
  /// Base64 text of bytes.
  Base64
  /// ISO 8601 text of a timestamp.
  Timestamp
  /// Decimal text of an integer.
  Integer
}

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

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

///|
/// A fault when a codec encodes or decodes a payload value. Each case holds the
/// path to the failed value.
#derive(Debug)
pub suberror CodecError {
  /// The value at `path` is `found`, but the codec needs `expected`.
  TypeMismatch(path~ : Path, expected~ : ValueKind, found~ : ValueKind)
  /// The array at `path` has `found` items, but the codec needs `expected`.
  /// For the arguments of a method, the numbers are the number of parameters
  /// and the number of arguments.
  LengthMismatch(path~ : Path, expected~ : Int32, found~ : Int32)
  /// The object at `path` has no property `name`.
  MissingProperty(path~ : Path, name~ : String)
  /// The number at `path` is not exactly an integer of 64 bits. `value` is the
  /// nearest double.
  NotAnInteger(path~ : Path, value~ : Double)
  /// The integer `value` at `path` is outside the range from `min` to `max`.
  IntegerOutOfRange(path~ : Path, value~ : String, min~ : String, max~ : String)
  /// The double at `path` is NaN or infinite.
  NotFinite(path~ : Path, value~ : Double)
  /// The value at `path` is not a case of the enum.
  UnknownEnumValue(path~ : Path, value~ : String)
  /// The text at `path` is not valid in the form `format`.
  InvalidText(path~ : Path, format~ : TextFormat, text~ : String)
  /// The value inside an `option` at `path` encodes as null, which a decode would
  /// read as `None`.
  NullInOption(path~ : Path)
  /// The smart constructor of a domain type rejected the value at `path` with
  /// the error `cause`.
  Rejected(path~ : Path, cause~ : Error)
}

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

///|
/// The path to the failed value.
pub fn CodecError::path(self : CodecError) -> Path {
  match self {
    TypeMismatch(path~, ..)
    | LengthMismatch(path~, ..)
    | MissingProperty(path~, ..)
    | NotAnInteger(path~, ..)
    | IntegerOutOfRange(path~, ..)
    | NotFinite(path~, ..)
    | UnknownEnumValue(path~, ..)
    | InvalidText(path~, ..)
    | NullInOption(path~)
    | Rejected(path~, ..) => path
  }
}

///|
/// Text for people that describes the fault.
pub fn CodecError::message(self : CodecError) -> String {
  match self {
    TypeMismatch(path~, expected~, found~) =>
      "\{path}: expected \{expected.label()}, found \{found.label()}"
    LengthMismatch(path~, expected~, found~) =>
      "\{path}: expected \{expected} items, found \{found}"
    MissingProperty(path~, name~) =>
      "\{path}: the property \{name.escape()} is missing"
    NotAnInteger(path~, value~) =>
      "\{path}: the number \{value} is not an exact 64-bit integer"
    IntegerOutOfRange(path~, value~, min~, max~) =>
      "\{path}: the integer \{value} is outside the range \{min} to \{max}"
    NotFinite(path~, value~) => "\{path}: the number \{value} is not finite"
    UnknownEnumValue(path~, value~) =>
      "\{path}: \{value} is not a case of the enum"
    InvalidText(path~, format~, text~) => {
      let form = match format {
        Base64 => "Base64"
        Timestamp => "ISO 8601 timestamp"
        Integer => "integer"
      }
      "\{path}: \{text.escape()} is not valid \{form} text"
    }
    NullInOption(path~) =>
      "\{path}: a value that encodes as null cannot be inside an option"
    Rejected(path~, cause~) => "\{path}: \{cause}"
  }
}

///|
/// The conversion of a MoonBit type `T` to and from a payload value (design
/// CDC-2). A decode builds a domain value only through its smart constructor;
/// see `Codec::parse`.
pub struct Codec[T] {
  priv encoder : (T, Path) -> HubValue raise CodecError
  priv decoder : (HubValue, Path) -> T raise CodecError
  /// The value when a record property is missing, or `None` when a missing
  /// property is an error.
  priv absent : T?
  /// The codec of `unit()`, for a method with no result.
  priv no_result : Bool
}

///|
/// A codec from an encode function and a decode function. Each function gets the
/// path of the value for its errors.
pub fn[T] Codec::new(
  encode~ : (T, Path) -> HubValue raise CodecError,
  decode~ : (HubValue, Path) -> T raise CodecError,
) -> Codec[T] {
  { encoder: encode, decoder: decode, absent: None, no_result: false, }
}

///|
/// True for `unit()`: a method with this result codec has no result, so its
/// Completion holds none.
pub fn[T] Codec::has_no_result(self : Codec[T]) -> Bool {
  self.no_result
}

///|
/// Encode `value`. `path` names the value in errors; the default is `$`.
pub fn[T] Codec::encode(
  self : Codec[T],
  value : T,
  path~ : Path = Path::root(),
) -> HubValue raise CodecError {
  (self.encoder)(value, path)
}

///|
/// Decode `value`. `path` names the value in errors; the default is `$`.
pub fn[T] Codec::decode(
  self : Codec[T],
  value : HubValue,
  path~ : Path = Path::root(),
) -> T raise CodecError {
  (self.decoder)(value, path)
}

///|
/// A codec for `B` that decodes an `A` and then runs `parse`, the smart
/// constructor of `B`. An error of `parse` becomes `Rejected` with the path and
/// that error. `to_raw` gives the `A` of a `B` to encode.
pub fn[A, B] Codec::parse(
  self : Codec[A],
  parse : (A) -> B raise?,
  to_raw : (B) -> A,
) -> Codec[B] {
  {
    encoder: (value, path) => (self.encoder)(to_raw(value), path),
    decoder: (value, path) => {
      let raw = (self.decoder)(value, path)
      // A closure with the general error type, so that the error of any smart
      // constructor becomes the cause.
      let run : (A) -> B raise = raw => parse(raw)
      run(raw) catch {
        cause => raise Rejected(path~, cause~)
      }
    },
    absent: None,
    no_result: false,
  }
}

///|
/// A codec for `B` through two total functions.
pub fn[A, B] Codec::map(
  self : Codec[A],
  from : (A) -> B,
  to : (B) -> A,
) -> Codec[B] {
  {
    encoder: (value, path) => (self.encoder)(to(value), path),
    decoder: (value, path) => from((self.decoder)(value, path)),
    absent: self.absent.map(from),
    no_result: false,
  }
}

///|
fn mismatch(path : Path, expected : ValueKind, found : HubValue) -> CodecError {
  TypeMismatch(path~, expected~, found=found.kind())
}

///|
/// The codec of a payload value itself.
pub fn hub_value() -> Codec[HubValue] {
  Codec::new(encode=(value, _) => value, decode=(value, _) => value)
}

///|
/// `()` as null. Use it for a method with no result.
pub fn unit() -> Codec[Unit] {
  {
    encoder: (_, _) => Null,
    decoder: (value, path) => {
      guard value is Null else { raise mismatch(path, Null, value) }
    },
    absent: None,
    no_result: true,
  }
}

///|
/// A boolean.
pub fn bool() -> Codec[Bool] {
  Codec::new(encode=(value, _) => Bool(value), decode=(value, path) => {
    guard value is Bool(flag) else { raise mismatch(path, Bool, value) }
    flag
  })
}

///|
/// A string.
pub fn string() -> Codec[String] {
  Codec::new(encode=(value, _) => String(value), decode=(value, path) => {
    guard value is String(text) else { raise mismatch(path, String, value) }
    text
  })
}

///|
/// The largest integer that a JavaScript number holds exactly: 2^53 - 1.
pub let max_safe_integer : Int64 = 9007199254740991L

///|
/// An integer in a payload value as a sign and a magnitude, so that the full
/// range of `Int64` and `UInt64` compares with no overflow.
priv struct Whole {
  negative : Bool
  magnitude : UInt64
}

///|
fn Whole::to_string(self : Whole) -> String {
  if self.negative {
    "-\{self.magnitude}"
  } else {
    self.magnitude.to_string()
  }
}

///|
fn whole_of_int64(value : Int64) -> Whole {
  if value < 0L {
    // The magnitude of -2^63 is 2^63, which UInt64 holds.
    {
      negative: true,
      magnitude: (-(value + 1L)).reinterpret_as_uint64() + 1UL,
    }
  } else {
    { negative: false, magnitude: value.reinterpret_as_uint64(), }
  }
}

///|
/// The integer of `value`. A double is never an integer, also when it has no
/// fraction: it can be the rounded value of a number that is not one.
fn whole_of(value : HubValue, path : Path) -> Whole raise CodecError {
  match value {
    Int(number) => whole_of_int64(number)
    UInt(number) => { negative: false, magnitude: number, }
    Double(number) => raise NotAnInteger(path~, value=number.value())
    _ => raise mismatch(path, Integer, value)
  }
}

///|
/// Check that `whole` is from `min` to `max`, and give it as an `Int64`.
fn whole_in_range(
  whole : Whole,
  min : Int64,
  max : Int64,
  path : Path,
) -> Int64 raise CodecError {
  let low = whole_of_int64(min)
  let high = whole_of_int64(max)
  let below = if whole.negative {
    !low.negative || whole.magnitude > low.magnitude
  } else {
    false
  }
  let above = if whole.negative {
    false
  } else {
    !high.negative && whole.magnitude > high.magnitude
  }
  guard !below && !above else {
    raise IntegerOutOfRange(
      path~,
      value=whole.to_string(),
      min=min.to_string(),
      max=max.to_string(),
    )
  }
  if whole.negative {
    -(whole.magnitude - 1UL).reinterpret_as_int64() - 1L
  } else {
    whole.magnitude.reinterpret_as_int64()
  }
}

///|
/// A 32-bit integer as a number.
pub fn int() -> Codec[Int32] {
  Codec::new(encode=(value, _) => Int(value.to_int64()), decode=(value, path) => {
    whole_in_range(whole_of(value, path), -2147483648L, 2147483647L, path).to_int()
  })
}

///|
/// A 64-bit integer as a number, only from -(2^53 - 1) to 2^53 - 1, so that a
/// JavaScript client reads it exactly. Encode and decode raise
/// `IntegerOutOfRange` with the safe range for another value. Use
/// `int64_as_text` for the full range.
pub fn int64() -> Codec[Int64] {
  Codec::new(
    encode=(value, path) => {
      Int(
        whole_in_range(
          whole_of_int64(value),
          -max_safe_integer,
          max_safe_integer,
          path,
        ),
      )
    },
    decode=(value, path) => {
      whole_in_range(
        whole_of(value, path),
        -max_safe_integer,
        max_safe_integer,
        path,
      )
    },
  )
}

///|
/// Read the decimal text of an integer: an optional `-` and one or more ASCII
/// digits, with no other character.
fn whole_of_text(text : String, path : Path) -> Whole raise CodecError {
  let invalid = () => InvalidText(path~, format=Integer, text~)
  let negative = text.has_prefix("-")
  let digits = if negative { text[1:].to_owned() } else { text }
  guard !digits.is_empty() else { raise invalid() }
  let mut magnitude = 0UL
  for char in digits {
    guard is_ascii_digit(char) else { raise invalid() }
    let digit = (char.to_int() - '0'.to_int()).to_uint64()
    guard magnitude <= (18446744073709551615UL - digit) / 10UL else {
      raise IntegerOutOfRange(
        path~,
        value=text,
        min="-18446744073709551615",
        max="18446744073709551615",
      )
    }
    magnitude = magnitude * 10UL + digit
  }
  // `-0` is zero.
  { negative: negative && magnitude != 0UL, magnitude, }
}

///|
/// A 64-bit integer as decimal text, for the full range of `Int64`. Decode also
/// reads a number. This is an explicit choice, as `JsonNumberHandling.WriteAsString`
/// is in .NET.
pub fn int64_as_text() -> Codec[Int64] {
  Codec::new(encode=(value, _) => String(value.to_string()), decode=(
    value,
    path,
  ) => {
    let whole = match value {
      String(text) => whole_of_text(text, path)
      _ => whole_of(value, path)
    }
    whole_in_range(
      whole,
      -9223372036854775807L - 1L,
      9223372036854775807L,
      path,
    )
  })
}

///|
/// Check that `whole` is from 0 to `max`, and give it as a `UInt64`.
fn whole_in_unsigned_range(
  whole : Whole,
  max : UInt64,
  path : Path,
) -> UInt64 raise CodecError {
  guard (!whole.negative || whole.magnitude == 0UL) && whole.magnitude <= max else {
    raise IntegerOutOfRange(
      path~,
      value=whole.to_string(),
      min="0",
      max=max.to_string(),
    )
  }
  whole.magnitude
}

///|
/// An unsigned 64-bit integer as a number, only from 0 to 2^53 - 1. Use
/// `uint64_as_text` for the full range.
pub fn uint64() -> Codec[UInt64] {
  let max = max_safe_integer.reinterpret_as_uint64()
  Codec::new(
    encode=(value, path) => {
      UInt(
        whole_in_unsigned_range(
          { negative: false, magnitude: value, },
          max,
          path,
        ),
      )
    },
    decode=(value, path) => {
      whole_in_unsigned_range(whole_of(value, path), max, path)
    },
  )
}

///|
/// An unsigned 64-bit integer as decimal text, for the full range of `UInt64`.
/// Decode also reads a number.
pub fn uint64_as_text() -> Codec[UInt64] {
  Codec::new(encode=(value, _) => String(value.to_string()), decode=(
    value,
    path,
  ) => {
    let whole = match value {
      String(text) => whole_of_text(text, path)
      _ => whole_of(value, path)
    }
    whole_in_unsigned_range(whole, 18446744073709551615UL, path)
  })
}

///|
/// A finite double. Encode raises `NotFinite` for NaN and infinity, as
/// System.Text.Json does by default. Decode also reads an integer.
pub fn double() -> Codec[Double] {
  Codec::new(
    encode=(value, path) => {
      let finite = FiniteDouble::parse(value) catch {
        _ => raise NotFinite(path~, value~)
      }
      Double(finite)
    },
    decode=(value, path) => {
      match value {
        Double(number) => number.value()
        Int(number) => number.to_double()
        UInt(number) => number.to_double()
        _ => raise mismatch(path, Double, value)
      }
    },
  )
}

///|
/// Bytes. The JSON encoding writes them as Base64 text with padding, so decode
/// also reads Base64 text.
pub fn bytes() -> Codec[Bytes] {
  Codec::new(encode=(value, _) => Bytes(value), decode=(value, path) => {
    match value {
      Bytes(data) => data
      String(text) =>
        @base64.decode(text) catch {
          _ => raise InvalidText(path~, format=Base64, text~)
        }
      _ => raise mismatch(path, Bytes, value)
    }
  })
}

///|
/// A timestamp. The JSON encoding writes it as ISO 8601 text, so decode also
/// reads that text.
pub fn timestamp() -> Codec[Timestamp] {
  Codec::new(encode=(value, _) => Timestamp(value), decode=(value, path) => {
    match value {
      Timestamp(instant) => instant
      String(text) =>
        Timestamp::parse(text) catch {
          _ => raise InvalidText(path~, format=Timestamp, text~)
        }
      _ => raise mismatch(path, Timestamp, value)
    }
  })
}