// JSON decoding helpers. All readers carry a real `@cjson.DecodeContext` so
// errors raise `@cjson.JsonDecodeError` with RFC 6901 JSON Pointer locations,
// allowing generated `FromJson` impls to match the core trait signature directly.

///|
/// Internal helper to obtain a genuine `@cjson.DecodeContext` root value
/// (its `Root` constructor is private to `moonbitlang/core/json`).
priv struct ContextCapture {
  ctx : @cjson.DecodeContext
}

///|
impl @cjson.FromJson for ContextCapture with fn from_json(_, ctx) {
  { ctx: ctx.copy(), }
}

///|
let cached_root_ctx : @cjson.DecodeContext = {
  let captured : ContextCapture = @cjson.from_json(@cjson.Json::null()) catch {
    _ => abort("unreachable: ContextCapture::from_json never fails")
  }
  captured.ctx
}

///|
fn root_decode_context() -> @cjson.DecodeContext {
  cached_root_ctx.copy()
}

///|
/// Parse JSON text with `preserve_number_repr=true` so 64-bit integers never
/// lose precision to IEEE-754 doubles.
pub fn parse_json(text : String) -> @cjson.Json raise @cjson.ParseError {
  @cjson.parse(text, preserve_number_repr=true)
}

///|
/// A positioned view over one JSON value with its structured `DecodeContext`.
pub struct JsonReader {
  priv node : @cjson.Json
  priv ctx : @cjson.DecodeContext
}

///|
/// Wrap a JSON value with the `DecodeContext` passed into `FromJson::from_json`.
pub fn JsonReader::new(
  node : @cjson.Json,
  ctx : @cjson.DecodeContext,
) -> JsonReader {
  { node, ctx: ctx.copy(), }
}

///|
/// Wrap a root JSON value without an existing `DecodeContext`.
pub fn JsonReader::root(node : @cjson.Json) -> JsonReader {
  { node, ctx: root_decode_context(), }
}

///|
pub fn JsonReader::raw(self : JsonReader) -> @cjson.Json {
  self.node
}

///|
pub fn JsonReader::context(self : JsonReader) -> @cjson.DecodeContext {
  self.ctx.copy()
}

///|
/// Current RFC 6901 JSON Pointer path (e.g. `"/items/0/id"`).
pub fn JsonReader::path(self : JsonReader) -> String {
  self.ctx.to_string()
}

///|
/// Build a `@cjson.JsonDecodeError` anchored at this reader's current path.
pub fn JsonReader::error(
  self : JsonReader,
  message : String,
) -> @cjson.JsonDecodeError {
  self.ctx.error(message)
}

///|
pub fn JsonReader::is_null(self : JsonReader) -> Bool {
  self.node is @cjson.Null
}

///|
pub fn JsonReader::read_null(
  self : JsonReader,
) -> Unit raise @cjson.JsonDecodeError {
  if !(self.node is @cjson.Null) {
    raise self.ctx.error("expected null")
  }
}

///|
pub fn JsonReader::read_string(
  self : JsonReader,
) -> String raise @cjson.JsonDecodeError {
  match self.node {
    @cjson.String(text) => text
    _ => raise self.ctx.error("expected string")
  }
}

///|
pub fn JsonReader::read_bool(
  self : JsonReader,
) -> Bool raise @cjson.JsonDecodeError {
  match self.node {
    @cjson.True => true
    @cjson.False => false
    _ => raise self.ctx.error("expected boolean")
  }
}

///|
/// Extract exact number text from a JSON number (using preserved `repr` when
/// available). JSON strings are intentionally NOT accepted here so integer
/// readers cannot silently coerce strings.
fn number_text(node : @cjson.Json) -> String? {
  match node {
    @cjson.Number(_, repr=Some(text)) => Some(text)
    @cjson.Number(_, repr=None) => Some(node.stringify())
    _ => None
  }
}

///|
/// Normalize an RFC 8259 JSON number text representing an exact integer
/// (including `.0`, `-0`, and scientific notation like `1e5` or `1.5e2`) into
/// canonical decimal integer digits (with optional leading `-`, never `"-0"`).
/// Returns `None` for non-integers, malformed numbers, or magnitudes exceeding
/// 21 decimal digits (preventing DoS on inputs like `1e1000000000`).
fn normalize_json_integer(text : String) -> String? {
  let len = text.length()
  if len == 0 {
    return None
  }
  let mut idx = 0
  let mut negative = false
  if text.code_unit_at(0).to_int() == 0x2D {
    negative = true
    idx = 1
  }
  if idx >= len {
    return None
  }
  let digits = StringBuilder()
  let mut int_count = 0
  while idx < len {
    let c = text.code_unit_at(idx).to_int()
    if c >= 0x30 && c <= 0x39 {
      digits.write_char(c.unsafe_to_char())
      int_count += 1
      idx += 1
    } else {
      break
    }
  }
  if int_count == 0 {
    return None
  }
  let mut frac_count = 0
  if idx < len && text.code_unit_at(idx).to_int() == 0x2E {
    idx += 1
    while idx < len {
      let c = text.code_unit_at(idx).to_int()
      if c >= 0x30 && c <= 0x39 {
        digits.write_char(c.unsafe_to_char())
        frac_count += 1
        idx += 1
      } else {
        break
      }
    }
    if frac_count == 0 {
      return None
    }
  }
  let mut exp : Int64 = 0L
  if idx < len {
    let ec = text.code_unit_at(idx).to_int()
    if ec == 0x65 || ec == 0x45 {
      idx += 1
      let mut exp_neg = false
      if idx < len {
        let sc = text.code_unit_at(idx).to_int()
        if sc == 0x2D {
          exp_neg = true
          idx += 1
        } else if sc == 0x2B {
          idx += 1
        }
      }
      let mut exp_digits = 0
      while idx < len {
        let c = text.code_unit_at(idx).to_int()
        if c >= 0x30 && c <= 0x39 {
          if exp < 1_000_000L {
            exp = exp * 10L + (c - 0x30).to_int64()
          }
          exp_digits += 1
          idx += 1
        } else {
          break
        }
      }
      if exp_digits == 0 {
        return None
      }
      if exp_neg {
        exp = -exp
      }
    }
  }
  if idx != len {
    return None
  }
  let raw_digits = digits.to_string()
  let mut start = 0
  while start < raw_digits.length() &&
        raw_digits.code_unit_at(start).to_int() == 0x30 {
    start += 1
  }
  if start == raw_digits.length() {
    return Some("0")
  }
  let sig = raw_digits[start:].to_owned()
  let eff_exp = exp - frac_count.to_int64()
  let out = StringBuilder()
  if negative {
    out.write_char('-')
  }
  if eff_exp >= 0L {
    if sig.length().to_int64() + eff_exp > 21L {
      return None
    }
    out.write_string(sig)
    for _ in 0.. sig.length() {
      return None
    }
    let keep = sig.length() - shift
    for i in keep.. Int64 raise @cjson.JsonDecodeError {
  match number_text(self.node) {
    Some(text) =>
      match normalize_json_integer(text) {
        Some(norm) =>
          match parse_int64_text(norm) {
            Some(value) => value
            None => raise self.ctx.error("\{type_name} out of range: \{text}")
          }
        None => raise self.ctx.error("expected \{type_name}, got \{text}")
      }
    None => raise self.ctx.error("expected \{type_name}")
  }
}

///|
fn JsonReader::read_unsigned_exact(
  self : JsonReader,
  type_name : String,
) -> UInt64 raise @cjson.JsonDecodeError {
  match number_text(self.node) {
    Some(text) =>
      match normalize_json_integer(text) {
        Some(norm) =>
          if norm.has_prefix("-") {
            raise self.ctx.error("\{type_name} out of range: \{text}")
          } else {
            match parse_uint64_text(norm) {
              Some(value) => value
              None => raise self.ctx.error("\{type_name} out of range: \{text}")
            }
          }
        None => raise self.ctx.error("expected \{type_name}, got \{text}")
      }
    None => raise self.ctx.error("expected \{type_name}")
  }
}

///|
/// Int64 from a JSON number (using preserved repr). Supports full signed
/// 64-bit range including `Int64::MIN` (`-9223372036854775808`).
pub fn JsonReader::read_int64(
  self : JsonReader,
) -> Int64 raise @cjson.JsonDecodeError {
  self.read_signed_exact("int64")
}

///|
pub fn JsonReader::read_int32(
  self : JsonReader,
) -> Int32 raise @cjson.JsonDecodeError {
  let value = self.read_signed_exact("int32")
  if value >= -2147483648L && value <= 2147483647L {
    value.to_int()
  } else {
    raise self.ctx.error("int32 out of range: \{value}")
  }
}

///|
pub fn JsonReader::read_int16(
  self : JsonReader,
) -> Int16 raise @cjson.JsonDecodeError {
  let value = self.read_signed_exact("int16")
  if value >= -32768L && value <= 32767L {
    Int16::from_int64(value)
  } else {
    raise self.ctx.error("int16 out of range: \{value}")
  }
}

///|
/// UInt64 from a JSON number (using preserved repr). Supports full
/// `0..=18446744073709551615` without double precision loss.
pub fn JsonReader::read_uint64(
  self : JsonReader,
) -> UInt64 raise @cjson.JsonDecodeError {
  self.read_unsigned_exact("uint64")
}

///|
pub fn JsonReader::read_uint32(
  self : JsonReader,
) -> UInt32 raise @cjson.JsonDecodeError {
  let value = self.read_unsigned_exact("uint32")
  if value <= 4294967295UL {
    value.to_uint()
  } else {
    raise self.ctx.error("uint32 out of range: \{value}")
  }
}

///|
pub fn JsonReader::read_uint16(
  self : JsonReader,
) -> UInt16 raise @cjson.JsonDecodeError {
  let value = self.read_unsigned_exact("uint16")
  if value <= 65535UL {
    value.to_int().to_uint16()
  } else {
    raise self.ctx.error("uint16 out of range: \{value}")
  }
}

///|
pub fn JsonReader::read_byte(
  self : JsonReader,
) -> Byte raise @cjson.JsonDecodeError {
  let value = self.read_unsigned_exact("byte (uint8)")
  if value <= 255UL {
    value.to_int().to_byte()
  } else {
    raise self.ctx.error("byte (uint8) out of range: \{value}")
  }
}

///|
/// Char from a single-character JSON string.
pub fn JsonReader::read_char(
  self : JsonReader,
) -> Char raise @cjson.JsonDecodeError {
  let text = self.read_string()
  let mut count = 0
  let mut result : Char = '\u{0}'
  for ch in text {
    count += 1
    result = ch
    if count > 1 {
      raise self.ctx.error("expected single-character string")
    }
  }
  if count == 1 {
    result
  } else {
    raise self.ctx.error("expected single-character string")
  }
}

///|
/// Double from a finite JSON number.
pub fn JsonReader::read_double(
  self : JsonReader,
) -> Double raise @cjson.JsonDecodeError {
  match self.node {
    @cjson.Number(d, ..) =>
      if d.is_nan() || d.is_inf() {
        raise self.ctx.error("non-finite number")
      } else {
        d
      }
    _ => raise self.ctx.error("expected number")
  }
}

///|
/// Bytes decoded from standard base64 text (RFC 4648).
pub fn JsonReader::read_base64(
  self : JsonReader,
) -> Bytes raise @cjson.JsonDecodeError {
  let text = self.read_string()
  base64_decode(text, ctx=self.ctx)
}

///|
/// RFC 3339 date-time parsed into a UTC `@time.ZonedDateTime`.
pub fn JsonReader::read_datetime(
  self : JsonReader,
) -> @time.ZonedDateTime raise @cjson.JsonDecodeError {
  rfc3339_parse(self.read_string(), ctx=self.ctx)
}

///|
/// Array view: one path-tracked reader per element.
pub fn JsonReader::read_array(
  self : JsonReader,
) -> Array[JsonReader] raise @cjson.JsonDecodeError {
  match self.node {
    @cjson.Array(items) => {
      let out : Array[JsonReader] = []
      for i, item in items {
        out.push(JsonReader::new(item, self.ctx.add_index(i)))
      }
      out
    }
    _ => raise self.ctx.error("expected array")
  }
}

///|
/// Object entries as `(key, JsonReader)` pairs.
pub fn JsonReader::read_object(
  self : JsonReader,
) -> Array[(String, JsonReader)] raise @cjson.JsonDecodeError {
  match self.node {
    @cjson.Object(fields) => {
      let out : Array[(String, JsonReader)] = []
      for k, v in fields {
        out.push((k, JsonReader::new(v, self.ctx.add_key(k))))
      }
      out
    }
    _ => raise self.ctx.error("expected object")
  }
}

///|
/// Decode a JSON object into a typed `Map[String, T]`.
pub fn[T] JsonReader::read_map(
  self : JsonReader,
  decode : (JsonReader) -> T raise @cjson.JsonDecodeError,
) -> Map[String, T] raise @cjson.JsonDecodeError {
  let out : Map[String, T] = Map([])
  for entry in self.read_object() {
    let (k, reader) = entry
    out[k] = decode(reader)
  }
  out
}

///|
/// Decode a JSON object into a typed `Map[String, T]`, skipping `skip_key`
/// (used for `TaggedEnum` variants whose payload is a `Map[String, T]`
/// sharing the same JSON object as the discriminator tag property).
pub fn[T] JsonReader::read_map_excluding(
  self : JsonReader,
  skip_key : String,
  decode : (JsonReader) -> T raise @cjson.JsonDecodeError,
) -> Map[String, T] raise @cjson.JsonDecodeError {
  let out : Map[String, T] = Map([])
  for entry in self.read_object() {
    let (k, reader) = entry
    if k == skip_key {
      continue
    }
    out[k] = decode(reader)
  }
  out
}

///|
/// Reader for an optional object field (`None` when absent; raises if `self`
/// is not a JSON object).
pub fn JsonReader::opt_field(
  self : JsonReader,
  name : String,
) -> JsonReader? raise @cjson.JsonDecodeError {
  match self.node {
    @cjson.Object(fields) =>
      match fields.get(name) {
        Some(value) => Some(JsonReader::new(value, self.ctx.add_key(name)))
        None => None
      }
    _ => raise self.ctx.error("expected object")
  }
}

///|
/// Reader for a required object field (raises at `/…/` if missing).
pub fn JsonReader::field(
  self : JsonReader,
  name : String,
) -> JsonReader raise @cjson.JsonDecodeError {
  match self.opt_field(name) {
    Some(reader) => reader
    None => raise self.ctx.add_key(name).error("missing required field")
  }
}

///|
/// Decode a required non-null field.
pub fn[T] JsonReader::req_field(
  self : JsonReader,
  name : String,
  decode : (JsonReader) -> T raise @cjson.JsonDecodeError,
) -> T raise @cjson.JsonDecodeError {
  decode(self.field(name))
}

///|
/// Decode a required-nullable field: key MUST be present; `null` yields `None`.
pub fn[T] JsonReader::req_nullable_field(
  self : JsonReader,
  name : String,
  decode : (JsonReader) -> T raise @cjson.JsonDecodeError,
) -> T? raise @cjson.JsonDecodeError {
  let r = self.field(name)
  if r.is_null() {
    None
  } else {
    Some(decode(r))
  }
}

///|
/// Decode an optional (or optional-nullable) field: absent OR `null` yields
/// `None`; otherwise `Some(decode(r))`.
pub fn[T] JsonReader::opt_field_as(
  self : JsonReader,
  name : String,
  decode : (JsonReader) -> T raise @cjson.JsonDecodeError,
) -> T? raise @cjson.JsonDecodeError {
  match self.opt_field(name) {
    None => None
    Some(r) => if r.is_null() { None } else { Some(decode(r)) }
  }
}

///|
/// Standard RFC 4648 base64 encode (with `=` padding).
pub fn base64_encode(bytes : Bytes) -> String {
  @base64.encode(bytes[:])
}

///|
/// Strict RFC 4648 standard base64 decode (rejects malformed characters and
/// bad padding).
pub fn base64_decode(
  text : String,
  ctx? : @cjson.DecodeContext,
) -> Bytes raise @cjson.JsonDecodeError {
  let err_ctx = match ctx {
    Some(c) => c
    None => root_decode_context()
  }
  @base64.decode(text[:]) catch {
    _ => raise err_ctx.error("invalid base64 data")
  }
}

///|
fn is_signed_ascii_decimal(text : String) -> Bool {
  if text.is_empty() {
    return false
  }
  let mut started = false
  let mut saw_digit = false
  for ch in text {
    if !started {
      started = true
      if ch == '-' || ch == '+' {
        continue
      }
    }
    if !(ch is ('0'..<='9')) {
      return false
    }
    saw_digit = true
  }
  saw_digit
}

///|
fn is_unsigned_ascii_decimal(text : String) -> Bool {
  if text.is_empty() {
    return false
  }
  for ch in text {
    if !(ch is ('0'..<='9')) {
      return false
    }
  }
  true
}

///|
/// Overflow-checked signed 64-bit decimal parser supporting the full range
/// `[-9223372036854775808, 9223372036854775807]` via `moonbitlang/core/string`.
pub fn parse_int64_text(text : String) -> Int64? {
  if !is_signed_ascii_decimal(text) {
    return None
  }
  Some(@string.parse_int64(text[:], radix=10)) catch {
    _ => None
  }
}

///|
/// Overflow-checked unsigned 64-bit decimal parser (`0..=18446744073709551615`)
/// via `moonbitlang/core/string`.
pub fn parse_uint64_text(text : String) -> UInt64? {
  if !is_unsigned_ascii_decimal(text) {
    return None
  }
  Some(@string.parse_uint64(text[:], radix=10)) catch {
    _ => None
  }
}