// Wire-faithful JSON encoders for generated `ToJson` impls: lossless
// `Int64`/`UInt64` numbers via `Json::number(_, repr=...)`, `Byte`/`Int16`/
// `UInt16`/`Char`, base64 `Bytes`, RFC 3339 `ZonedDateTime`, and `ObjectBuilder`.

///|
/// Encode a lossless 64-bit signed integer JSON number (preserving exact wire digits).
pub fn write_int64(value : Int64) -> @cjson.Json {
  @cjson.Json::number(value.to_double(), repr=value.to_string())
}

///|
/// Encode a lossless 64-bit unsigned integer JSON number (preserving exact wire digits).
pub fn write_uint64(value : UInt64) -> @cjson.Json {
  @cjson.Json::number(value.to_double(), repr=value.to_string())
}

///|
/// Encode a 32-bit signed integer as a JSON number.
pub fn write_int32(value : Int32) -> @cjson.Json {
  @cjson.Json::number(value.to_double(), repr=value.to_string())
}

///|
/// Encode a 32-bit unsigned integer as a JSON number.
pub fn write_uint32(value : UInt32) -> @cjson.Json {
  @cjson.Json::number(value.to_double(), repr=value.to_string())
}

///|
/// Encode a 16-bit signed integer as a JSON number.
pub fn write_int16(value : Int16) -> @cjson.Json {
  @cjson.Json::number(value.to_int().to_double(), repr=value.to_string())
}

///|
/// Encode a 16-bit unsigned integer as a JSON number.
pub fn write_uint16(value : UInt16) -> @cjson.Json {
  @cjson.Json::number(value.to_int().to_double(), repr=value.to_string())
}

///|
/// Encode an unsigned byte (`0..=255`) as a JSON number.
pub fn write_byte(value : Byte) -> @cjson.Json {
  let n = value.to_int()
  @cjson.Json::number(n.to_double(), repr=n.to_string())
}

///|
/// Encode a `Double` as a JSON number; non-finite values (`NaN`, `±Infinity`)
/// are encoded as `null` to guarantee valid RFC 8259 JSON.
pub fn write_double(value : Double) -> @cjson.Json {
  if value.is_nan() || value.is_inf() {
    @cjson.Json::null()
  } else {
    @cjson.Json::number(value)
  }
}

///|
/// Encode a boolean as a JSON boolean.
pub fn write_bool(value : Bool) -> @cjson.Json {
  @cjson.Json::boolean(value)
}

///|
/// Encode a string as a JSON string.
pub fn write_string(value : String) -> @cjson.Json {
  @cjson.Json::string(value)
}

///|
/// Encode a single Unicode scalar `Char` as a one-character JSON string.
pub fn write_char(value : Char) -> @cjson.Json {
  @cjson.Json::string(value.to_string())
}

///|
/// Encode raw bytes as a standard RFC 4648 base64 JSON string.
pub fn write_base64(bytes : Bytes) -> @cjson.Json {
  @cjson.Json::string(base64_encode(bytes))
}

///|
/// Encode a `@time.ZonedDateTime` as a canonical UTC RFC 3339 JSON string.
pub fn write_datetime(dt : @time.ZonedDateTime) -> @cjson.Json {
  @cjson.Json::string(rfc3339_format_utc(dt))
}

///|
/// Builder for JSON objects in generated `ToJson` impls.
pub struct ObjectBuilder {
  priv fields : Map[String, @cjson.Json]
}

///|
/// Create an empty `ObjectBuilder`.
pub fn ObjectBuilder::new() -> ObjectBuilder {
  { fields: Map([]), }
}

///|
/// Add a required field unconditionally.
pub fn ObjectBuilder::field(
  self : ObjectBuilder,
  wire : String,
  value : @cjson.Json,
) -> ObjectBuilder {
  self.fields[wire] = value
  self
}

///|
/// Add an optional field: `None` is omitted on the wire.
pub fn ObjectBuilder::opt_field(
  self : ObjectBuilder,
  wire : String,
  value : @cjson.Json?,
) -> ObjectBuilder {
  match value {
    Some(v) => self.fields[wire] = v
    None => ()
  }
  self
}

///|
/// Add a required-nullable field: `None` is encoded as JSON `null`.
pub fn ObjectBuilder::nullable_field(
  self : ObjectBuilder,
  wire : String,
  value : @cjson.Json?,
) -> ObjectBuilder {
  match value {
    Some(v) => self.fields[wire] = v
    None => self.fields[wire] = @cjson.Json::null()
  }
  self
}

///|
/// Merge all fields of another JSON object into this builder (used by
/// internally-tagged flattened union encoders so tag + payload share one object).
/// Existing keys (e.g. a discriminator tag written first or last) are overwritten
/// only if `overwrite` is `true` (default `false`, preserving the tag).
pub fn ObjectBuilder::merge_object(
  self : ObjectBuilder,
  other : @cjson.Json,
  overwrite~ : Bool = false,
) -> ObjectBuilder {
  match other {
    @cjson.Object(map) =>
      for k, v in map {
        if overwrite || !self.fields.contains(k) {
          self.fields[k] = v
        }
      }
    _ => ()
  }
  self
}

///|
/// Finalize and return the built JSON object.
pub fn ObjectBuilder::build(self : ObjectBuilder) -> @cjson.Json {
  let copy : Map[String, @cjson.Json] = Map([])
  for k, v in self.fields {
    copy[k] = v
  }
  @cjson.Json::object(copy)
}