///|
/// Check that JSON text has at most `max_depth` nested arrays and objects
/// outside strings. Runs before `@json.parse` so deep input is rejected on
/// every MoonBit toolchain without allocating a deep `Json` tree.
fn check_json_depth(
  text : StringView,
  max_depth : DepthLimit,
) -> Unit raise ProtocolError {
  let limit = max_depth.to_levels()
  let mut in_string = false
  let mut escaped = false
  let mut depth : Int32 = 0
  for char in text {
    if in_string {
      if escaped {
        escaped = false
      } else if char == '\\' {
        escaped = true
      } else if char == '"' {
        in_string = false
      }
    } else if char == '"' {
      in_string = true
    } else if char == '[' || char == '{' {
      depth += 1
      if depth > limit {
        raise MessageTooDeep(limit~)
      }
    } else if char == ']' || char == '}' {
      if depth > 0 {
        depth -= 1
      }
    }
  }
}

///|
/// Parse JSON text. Duplicate keys in an object and nesting deeper than
/// `max_depth` are errors.
fn parse_json(
  text : StringView,
  max_depth~ : DepthLimit = DepthLimit::default_message_depth(),
) -> Json raise ProtocolError {
  check_json_depth(text, max_depth)
  @json.parse(text, reject_duplicate_keys=true, preserve_number_repr=true) catch {
    err => raise InvalidJson(detail=err.to_string())
  }
}

///|
/// The integer that the JSON number `text` denotes exactly, or `None` when it has a
/// fraction or does not fit `Int64` or `UInt64`. The digits decide, and not the
/// nearest double: `1.0000000000000001` is not an integer, and `1.5e1` is 15.
fn exact_integer(text : String) -> HubValue? {
  let negative = text.has_prefix("-")
  // The digits with no leading zeros, and the power of ten that scales them.
  let digits : Array[Char] = []
  let mut scale = 0L
  let mut in_fraction = false
  let mut in_exponent = false
  let mut exponent = 0L
  let mut exponent_negative = false
  for char in text {
    match char {
      '.' => in_fraction = true
      'e' | 'E' => in_exponent = true
      '-' => if in_exponent { exponent_negative = true }
      '0'..<='9' if in_exponent =>
        // No text has this many digits, so a larger exponent gives the same result.
        if exponent < 1000000000000L {
          exponent = exponent * 10L + (char.to_int() - '0'.to_int()).to_int64()
        }
      '0'..<='9' => {
        if in_fraction {
          scale -= 1L
        }
        if char != '0' || !digits.is_empty() {
          digits.push(char)
        }
      }
      _ => ()
    }
  }
  scale += if exponent_negative { -exponent } else { exponent }
  while digits.last() is Some('0') {
    ignore(digits.pop())
    scale += 1L
  }
  if digits.is_empty() {
    return Some(Int(0L))
  }
  // 2^64 has 20 digits.
  guard scale >= 0L && digits.length().to_int64() + scale <= 20L else {
    return None
  }
  for _ in 0L.. 9223372036854775807UL {
        UInt(magnitude)
      } else {
        Int(magnitude.reinterpret_as_int64())
      },
    )
  }
  guard magnitude <= 9223372036854775808UL else { return None }
  Some(Int(-(magnitude - 1UL).reinterpret_as_int64() - 1L))
}

///|
priv enum FromJsonFrame {
  FromArray(items~ : Array[Json], index~ : Int32, out~ : Array[HubValue])
  FromObject(
    entries~ : Array[(String, Json)],
    index~ : Int32,
    out~ : Array[(String, HubValue)],
  )
}

///|
priv enum ToJsonFrame {
  ToArray(items~ : ReadOnlyArray[HubValue], index~ : Int32, out~ : Array[Json])
  ToObject(
    entries~ : ReadOnlyArray[(String, HubValue)],
    index~ : Int32,
    out~ : Map[String, Json],
  )
}

///|
/// The payload value of a JSON value. A number that is exactly an integer, also with
/// an exponent, gives `Int`, or `UInt` above the range of `Int64`. Another number
/// gives `Double`, so a `Double` from JSON is never an exact 64-bit integer. A JSON string
/// stays a string: a codec reads Base64 bytes and timestamps from it.
///
/// Raises `MessageTooDeep` when `json` has more nested arrays and objects than
/// `max_depth`. Uses an explicit stack so conversion never overflows the call
/// stack.
pub fn HubValue::from_json(
  json : Json,
  max_depth~ : DepthLimit = DepthLimit::default_message_depth(),
) -> HubValue raise ProtocolError {
  let limit = max_depth.to_levels()
  let stack : Array[FromJsonFrame] = []
  let mut current = json
  for ;; {
    let completed : HubValue? = match current {
      Null => Some(Null)
      True => Some(Bool(true))
      False => Some(Bool(false))
      Number(value, repr~) => Some(number_value(value, repr))
      String(text) => Some(String(text))
      Array(items) => {
        let next_depth = stack.length() + 1
        guard next_depth <= limit else { raise MessageTooDeep(limit~) }
        if items.is_empty() {
          Some(HubValue::array([]))
        } else {
          stack.push(
            FromArray(items~, index=1, out=Array(capacity=items.length())),
          )
          current = items[0]
          None
        }
      }
      Object(map) => {
        let next_depth = stack.length() + 1
        guard next_depth <= limit else { raise MessageTooDeep(limit~) }
        let entries = map.to_array()
        if entries.is_empty() {
          Some(Map(HubMap::empty()))
        } else {
          stack.push(
            FromObject(entries~, index=1, out=Array(capacity=entries.length())),
          )
          current = entries[0].1
          None
        }
      }
    }
    guard completed is Some(initial) else { continue }
    let mut value = initial
    for ;; {
      guard stack.pop() is Some(frame) else { return value }
      match frame {
        FromArray(items~, index~, out~) => {
          out.push(value)
          if index < items.length() {
            stack.push(FromArray(items~, index=index + 1, out~))
            current = items[index]
            break
          }
          value = HubValue::array(out)
        }
        FromObject(entries~, index~, out~) => {
          out.push((entries[index - 1].0, value))
          if index < entries.length() {
            stack.push(FromObject(entries~, index=index + 1, out~))
            current = entries[index].1
            break
          }
          // The parser rejects duplicate keys, so the map has unique keys.
          value = Map(
            HubMap::new(out) catch {
              _ => raise InvalidJson(detail="duplicate key")
            },
          )
        }
      }
    }
  }
}

///|
fn number_value(value : Double, repr : String?) -> HubValue raise ProtocolError {
  let text = repr.unwrap_or(value.to_string())
  if exact_integer(text) is Some(integer) {
    return integer
  }
  Double(
    FiniteDouble::parse(value) catch {
      _ => raise NumberOutOfRange(text~)
    },
  )
}

///|
/// The JSON value of a payload value: integers with their exact digits, bytes as
/// Base64 text with padding, and timestamps as ISO 8601 text in UTC. Uses an
/// explicit stack so deep values never overflow the call stack.
pub fn HubValue::to_json(self : HubValue) -> Json {
  let stack : Array[ToJsonFrame] = []
  let mut current = self
  for ;; {
    let completed : Json? = match current {
      Null => Some(Json::null())
      Bool(flag) => Some(Json::boolean(flag))
      Int(number) =>
        Some(Json::number(number.to_double(), repr=number.to_string()))
      UInt(number) =>
        Some(Json::number(number.to_double(), repr=number.to_string()))
      Double(number) => Some(Json::number(number.value()))
      String(text) => Some(Json::string(text))
      Bytes(data) => Some(Json::string(@base64.encode(data)))
      Timestamp(instant) => Some(Json::string(instant.to_string()))
      Array(items) =>
        if items.is_empty() {
          Some(Json::array([]))
        } else {
          stack.push(
            ToArray(items~, index=1, out=Array(capacity=items.length())),
          )
          current = items[0]
          None
        }
      Map(map) =>
        if map.entries.is_empty() {
          Some(Json::object(Map([])))
        } else {
          stack.push(ToObject(entries=map.entries, index=1, out=Map([])))
          current = map.entries[0].1
          None
        }
    }
    guard completed is Some(initial) else { continue }
    let mut value = initial
    for ;; {
      guard stack.pop() is Some(frame) else { return value }
      match frame {
        ToArray(items~, index~, out~) => {
          out.push(value)
          if index < items.length() {
            stack.push(ToArray(items~, index=index + 1, out~))
            current = items[index]
            break
          }
          value = Json::array(out)
        }
        ToObject(entries~, index~, out~) => {
          out[entries[index - 1].0] = value
          if index < entries.length() {
            stack.push(ToObject(entries~, index=index + 1, out~))
            current = entries[index].1
            break
          }
          value = Json::object(out)
        }
      }
    }
  }
}

///|
/// Read a payload value from JSON text.
pub fn HubValue::parse_json(
  text : StringView,
  max_depth~ : DepthLimit = DepthLimit::default_message_depth(),
) -> HubValue raise ProtocolError {
  HubValue::from_json(parse_json(text, max_depth~), max_depth~)
}

///|
/// The compact JSON text of a payload value.
pub fn HubValue::to_json_text(self : HubValue) -> String {
  self.to_json().stringify()
}