// Model type and explicit `FromJson`/`ToJson` codec emission (plan 5.1, 5.2).

///|
fn format_node_brief(node : @spec.Node) -> String {
  match node {
    @spec.Null => "null"
    @spec.Bool(b) => if b { "true" } else { "false" }
    @spec.Number(s) => s
    @spec.Str(s) => mbt_string_lit(s)
    @spec.Array(_) => "[...]"
    @spec.Object(_) => "{...}"
  }
}

///|
fn field_format_note(ft : @ir.FieldType) -> String? {
  match ft {
    @ir.Prim(@ir.Str(fmt)) if fmt != "" => Some(fmt)
    @ir.Prim(@ir.Int(fmt)) if fmt != "" => Some(fmt)
    @ir.Prim(@ir.Num(fmt)) if fmt != "" => Some(fmt)
    _ => None
  }
}

///|
/// Build structured field documentation combining the spec description with
/// presence, format, default, and deprecation notes.
fn build_field_doc(field : @ir.FieldIR) -> @doc.DocComment {
  let lines : Array[String] = []
  for l in field.docs {
    lines.push(l)
  }
  let notes : Array[String] = []
  match field.presence {
    @ir.Required => ()
    @ir.RequiredNullable => notes.push("Required, nullable")
    @ir.Optional => ()
    @ir.OptionalNullable => notes.push("Optional, nullable")
  }
  match field_format_note(field.type_) {
    Some(fmt) => notes.push("format: `\{fmt}`")
    None => ()
  }
  match field.default {
    Some(def) => notes.push("default: `\{format_node_brief(def)}`")
    None => ()
  }
  if field.read_only {
    notes.push("readOnly")
  }
  if field.write_only {
    notes.push("writeOnly")
  }
  let c = field.constraints
  match c.minimum {
    Some(v) => notes.push("min: `\{v}`")
    None => ()
  }
  match c.exclusive_minimum {
    Some(v) => notes.push("exclusiveMin: `\{v}`")
    None => ()
  }
  match c.maximum {
    Some(v) => notes.push("max: `\{v}`")
    None => ()
  }
  match c.exclusive_maximum {
    Some(v) => notes.push("exclusiveMax: `\{v}`")
    None => ()
  }
  match c.multiple_of {
    Some(v) => notes.push("multipleOf: `\{v}`")
    None => ()
  }
  match c.min_length {
    Some(v) => notes.push("minLength: `\{v}`")
    None => ()
  }
  match c.max_length {
    Some(v) => notes.push("maxLength: `\{v}`")
    None => ()
  }
  match c.pattern {
    Some(p) => notes.push("pattern: `\{p}`")
    None => ()
  }
  match c.min_items {
    Some(v) => notes.push("minItems: `\{v}`")
    None => ()
  }
  match c.max_items {
    Some(v) => notes.push("maxItems: `\{v}`")
    None => ()
  }
  if c.unique_items {
    notes.push("uniqueItems")
  }
  match c.min_properties {
    Some(v) => notes.push("minProperties: `\{v}`")
    None => ()
  }
  match c.max_properties {
    Some(v) => notes.push("maxProperties: `\{v}`")
    None => ()
  }
  if field.deprecated {
    notes.push("Deprecated")
  }
  if field.wire != field.name {
    notes.push("wire: `\{field.wire}`")
  }
  if !notes.is_empty() {
    if !lines.is_empty() {
      lines.push("")
    }
    lines.push(notes.join("; ") + ".")
  }
  @doc.DocComment::new(lines)
}

///|
fn deprecated_attrs(deprecated : Bool) -> Array[@doc.Attribute] {
  if deprecated {
    [@doc.Attribute::bare("deprecated")]
  } else {
    []
  }
}

///|
fn GenContext::emit_field_decode_stmt(
  self : GenContext,
  field : @ir.FieldIR,
  reader_var : String,
) -> String {
  let wire_lit = mbt_string_lit(field.wire)
  let inner_dec = self.emit_decode_expr(field.type_, "__fr", in_model=true)
  match field.presence {
    @ir.Required =>
      "let \{field.name} = \{reader_var}.req_field(\{wire_lit}, __fr => \{inner_dec})"
    @ir.RequiredNullable =>
      "let \{field.name} = \{reader_var}.req_nullable_field(\{wire_lit}, __fr => \{inner_dec})"
    @ir.Optional =>
      "let \{field.name} = \{reader_var}.opt_field_as(\{wire_lit}, __fr => \{inner_dec})"
    @ir.OptionalNullable =>
      if self.cfg.tri_state {
        "let \{field.name} = match \{reader_var}.opt_field(\{wire_lit}) { Option::None => NullableField::Absent; Option::Some(__fr) => if __fr.is_null() { NullableField::Null } else { NullableField::Value(\{inner_dec}) } }"
      } else {
        "let \{field.name} = \{reader_var}.opt_field_as(\{wire_lit}, __fr => \{inner_dec})"
      }
  }
}

///|
fn GenContext::emit_field_encode_call(
  self : GenContext,
  field : @ir.FieldIR,
  value_expr : String,
  obj_var~ : String = "__obj",
) -> String {
  let wire_lit = mbt_string_lit(field.wire)
  match field.presence {
    @ir.Required => {
      let enc = self.emit_encode_expr(field.type_, value_expr, in_model=true)
      "let _ = \{obj_var}.field(\{wire_lit}, \{enc})"
    }
    @ir.RequiredNullable => {
      let enc = self.emit_encode_expr(field.type_, "__fv", in_model=true)
      "let _ = \{obj_var}.nullable_field(\{wire_lit}, match \{value_expr} { Option::Some(__fv) => Option::Some(\{enc}); Option::None => Option::None })"
    }
    @ir.Optional => {
      let enc = self.emit_encode_expr(field.type_, "__fv", in_model=true)
      "let _ = \{obj_var}.opt_field(\{wire_lit}, match \{value_expr} { Option::Some(__fv) => Option::Some(\{enc}); Option::None => Option::None })"
    }
    @ir.OptionalNullable =>
      if self.cfg.tri_state {
        let enc = self.emit_encode_expr(field.type_, "__fv", in_model=true)
        "match \{value_expr} { NullableField::Absent => (); NullableField::Null => { let _ = \{obj_var}.nullable_field(\{wire_lit}, Option::None) }; NullableField::Value(__fv) => { let _ = \{obj_var}.field(\{wire_lit}, \{enc}) } }"
      } else {
        let enc = self.emit_encode_expr(field.type_, "__fv", in_model=true)
        "let _ = \{obj_var}.opt_field(\{wire_lit}, match \{value_expr} { Option::Some(__fv) => Option::Some(\{enc}); Option::None => Option::None })"
      }
  }
}

///|
fn make_from_json_impl(type_name : String, body : String) -> @doc.Item {
  @doc.item(
    @doc.DocComment::empty(),
    @doc.Decl::Impl({
      vis: @doc.Pub,
      type_params: [],
      method_type_params: [],
      self_type: @doc.Name(type_name),
      trait_: @doc.TypeExpr::qualified("cjson", "FromJson"),
      method_name: "from_json",
      params: [
        @doc.FnParam::positional(
          "json",
          @doc.TypeExpr::qualified("cjson", "Json"),
        ),
        @doc.FnParam::positional(
          "path",
          @doc.TypeExpr::qualified("cjson", "DecodeContext"),
        ),
      ],
      return_type: Some(@doc.Name(type_name)),
      error: @doc.TypedRaise(
        @doc.TypeExpr::qualified("cjson", "JsonDecodeError"),
      ),
      body,
    }),
  )
}

///|
fn make_to_json_impl(type_name : String, body : String) -> Array[@doc.Item] {
  [
    @doc.item(
      @doc.DocComment::empty(),
      @doc.Decl::Impl({
        vis: @doc.Pub,
        type_params: [],
        method_type_params: [],
        self_type: @doc.Name(type_name),
        trait_: @doc.TypeExpr::qualified("cjson", "ToJson"),
        method_name: "to_json",
        params: [@doc.FnParam::positional("self", @doc.Name(type_name))],
        return_type: Some(@doc.TypeExpr::qualified("cjson", "Json")),
        error: @doc.NoRaise,
        body,
      }),
    ),
    @doc.item(
      @doc.DocComment::empty(),
      @doc.Decl::Extend({
        vis: @doc.Pub,
        type_name: @doc.Name(type_name),
        trait_: @doc.TypeExpr::qualified("cjson", "ToJson"),
        methods: ["to_json"],
      }),
    ),
  ]
}

///|
fn GenContext::emit_record_def(
  self : GenContext,
  r : @ir.RecordDef,
  file : @doc.SourceFile,
) -> Unit {
  let type_name = self.type_name(r.name)
  let derives = self.derives_for(r.name)
  let fields : Array[@doc.StructField] = []
  for f in r.fields {
    fields.push({
      name: f.name,
      ty: self.struct_field_type(f, in_model=true),
      mut_: false,
      vis: @doc.Private,
      doc: build_field_doc(f),
      attrs: [],
    })
  }
  file.push(
    @doc.item_with_attrs(
      @doc.DocComment::new(r.docs),
      deprecated_attrs(r.deprecated),
      @doc.Decl::Struct({
        name: type_name,
        type_params: [],
        vis: @doc.PubAll,
        fields,
        derives,
      }),
    ),
  )
  // Ergonomic `Foo::new(req~, opt?)` constructor when record has optional fields
  let has_optional_field = r.fields.iter().any(f => f.presence.is_optional())
  let has_self_field = r.fields.iter().any(f => f.name == "self")
  if !r.fields.is_empty() && has_optional_field && !has_self_field {
    let req_params : Array[@doc.FnParam] = []
    let opt_params : Array[@doc.FnParam] = []
    for f in r.fields {
      let base_ty = self.field_type_expr(f.type_, in_model=true)
      match f.presence {
        @ir.Required => req_params.push(@doc.FnParam::labelled(f.name, base_ty))
        @ir.OptionalNullable if self.cfg.tri_state =>
          opt_params.push(
            @doc.FnParam::defaulted(
              f.name,
              self.struct_field_type(f, in_model=true),
              "NullableField::Absent",
            ),
          )
        _ => opt_params.push(@doc.FnParam::optional(f.name, base_ty))
      }
    }
    let ctor_params : Array[@doc.FnParam] = []
    for p in req_params {
      ctor_params.push(p)
    }
    for p in opt_params {
      ctor_params.push(p)
    }
    let ctor_inits = r.fields.map(f => "\{f.name},").join(" ")
    file.push(
      @doc.item(
        @doc.DocComment::new([
          "Construct a `\{type_name}` with optional fields defaulting to absent/`None`.",
        ]),
        @doc.Decl::Fn({
          self_type: Some(type_name),
          name: "new",
          type_params: [],
          params: ctor_params,
          return_type: Some(@doc.Name(type_name)),
          is_async: false,
          error: @doc.NoRaise,
          vis: @doc.Pub,
          body: "{ \{ctor_inits} }",
        }),
      ),
    )
  }
  // Hygienic internal variable names so record fields named `__r` / `__obj` never shadow.
  let local_namer = @name.Namer::new()
  local_namer.reserve("json")
  local_namer.reserve("path")
  local_namer.reserve("self")
  for f in r.fields {
    local_namer.reserve(f.name)
  }
  let r_var = local_namer.unique("__r")
  let obj_var = local_namer.unique("__obj")
  // FromJson
  let dec_lines : Array[String] = [
    "let \{r_var} = @rjson.JsonReader::new(json, path)",
  ]
  if r.fields.is_empty() {
    dec_lines.push("let _ = \{r_var}.read_object()")
    dec_lines.push("\{type_name}::{}")
  } else {
    for f in r.fields {
      dec_lines.push(self.emit_field_decode_stmt(f, r_var))
    }
    let field_inits = r.fields.map(f => "\{f.name},").join(" ")
    dec_lines.push("{ \{field_inits} }")
  }
  file.push(make_from_json_impl(type_name, dec_lines.join("\n")))
  // ToJson
  let enc_lines : Array[String] = [
    "let \{obj_var} = @rjson.ObjectBuilder::new()",
  ]
  if r.fields.is_empty() {
    enc_lines.push("ignore(self)")
  } else {
    for f in r.fields {
      enc_lines.push(self.emit_field_encode_call(f, "self.\{f.name}", obj_var~))
    }
  }
  enc_lines.push("\{obj_var}.build()")
  for it in make_to_json_impl(type_name, enc_lines.join("\n")) {
    file.push(it)
  }
  if self.cfg.emit_validators {
    file.push(self.emit_record_validator(type_name, r))
  }
}

///|
fn numeric_to_double_expr(ft : @ir.FieldType, v : String) -> String? {
  match ft {
    @ir.Prim(@ir.Num(_)) => Some(v)
    @ir.Prim(@ir.Int(fmt)) =>
      match fmt {
        "uint8" | "int16" | "uint16" => Some("\{v}.to_int().to_double()")
        _ => Some("\{v}.to_double()")
      }
    _ => None
  }
}

///|
/// Normalize a raw YAML/JSON numeric literal into a guaranteed-valid MoonBit
/// `Double` literal `(lit, is_strictly_positive)`, returning `None` for
/// non-finite values (`.inf`, `.nan`) or syntax that MoonBit rejects.
fn normalize_double_lit(raw : String) -> (String, Bool)? {
  let trimmed = raw.trim().to_owned()
  if trimmed.is_empty() {
    return None
  }
  let mut neg = false
  let mut s = trimmed
  if s.has_prefix("+") {
    s = s[1:].to_owned()
  } else if s.has_prefix("-") {
    neg = true
    s = s[1:].to_owned()
  }
  let cleaned = s.replace_all(old="_", new="")
  if cleaned.is_empty() {
    return None
  }
  // Split optional exponent `[eE][+-]?[0-9]+`
  let mut exp_idx : Int32? = None
  for i in 0.. (cleaned[:idx].to_owned(), cleaned[idx:].to_owned())
    None => (cleaned, "")
  }
  if mantissa_raw.is_empty() {
    return None
  }
  // Validate mantissa: digits and at most one `.`
  let mut dot_count : Int32 = 0
  let mut digit_count : Int32 = 0
  let mut has_nonzero = false
  for i in 0..= '0'.to_int() && cu <= '9'.to_int() {
      digit_count += 1
      if cu != '0'.to_int() {
        has_nonzero = true
      }
    } else if cu == '.'.to_int() {
      dot_count += 1
      if dot_count > 1 {
        return None
      }
    } else {
      return None
    }
  }
  if digit_count == 0 {
    return None
  }
  // Validate exponent if present
  if !exp_part.is_empty() {
    let mut j : Int32 = 1
    if j < exp_part.length() {
      let c = exp_part.code_unit_at(j).to_int()
      if c == '+'.to_int() || c == '-'.to_int() {
        j += 1
      }
    }
    if j >= exp_part.length() {
      return None
    }
    while j < exp_part.length() {
      let c = exp_part.code_unit_at(j).to_int()
      if c < '0'.to_int() || c > '9'.to_int() {
        return None
      }
      j += 1
    }
  }
  let m1 = if mantissa_raw.has_prefix(".") {
    "0" + mantissa_raw
  } else {
    mantissa_raw
  }
  let m2 = if m1.has_suffix(".") { m1 + "0" } else { m1 }
  let m3 = if dot_count == 0 && exp_part.is_empty() { m2 + ".0" } else { m2 }
  let lit = if neg { "-" + m3 + exp_part } else { m3 + exp_part }
  Some((lit, !neg && has_nonzero))
}

///|
fn parse_int64_str(raw : String) -> Int64? {
  if raw.is_empty() {
    return None
  }
  let mut i : Int32 = 0
  let mut neg = false
  if raw[0] == '-' {
    neg = true
    i = 1
  } else if raw[0] == '+' {
    i = 1
  }
  if i >= raw.length() {
    return None
  }
  let mut acc : Int64 = 0L
  while i < raw.length() {
    let c = raw[i]
    if c < '0' || c > '9' {
      return None
    }
    let d = (c.to_int() - '0'.to_int()).to_int64()
    if neg {
      if acc < (-9223372036854775808L + d) / 10L {
        return None
      }
      acc = acc * 10L - d
    } else {
      if acc > (9223372036854775807L - d) / 10L {
        return None
      }
      acc = acc * 10L + d
    }
    i += 1
  }
  Some(acc)
}

///|
/// Parse an exact signed/unsigned integer literal string suitable for native
/// integer comparisons (avoiding Double precision loss on Int64 / UInt64).
fn parse_exact_int_bound(raw : String, fmt : String) -> String? {
  let s = raw.trim().to_owned()
  if s.is_empty() || s.contains(".") || s.contains("e") || s.contains("E") {
    return None
  }
  match fmt {
    "uint64" => {
      if s.has_prefix("-") {
        return None
      }
      let clean = if s.has_prefix("+") { s[1:].to_owned() } else { s }
      if clean.is_empty() {
        return None
      }
      for ch in clean {
        if ch < '0' || ch > '9' {
          return None
        }
      }
      // Strip leading zeros while keeping a single "0".
      let mut nz = 0
      while nz + 1 < clean.length() && clean.code_unit_at(nz) == 0x30 {
        nz += 1
      }
      let norm = clean[nz:].to_owned()
      if norm.length() < 20 ||
        (norm.length() == 20 && norm <= "18446744073709551615") {
        Some("\{norm}UL")
      } else {
        None
      }
    }
    "int64" =>
      match parse_int64_str(s) {
        Some(v) => Some("\{v}L")
        None => None
      }
    "uint32" => {
      if s.has_prefix("-") {
        return None
      }
      match parse_int64_str(s) {
        Some(v) if v >= 0L && v <= 4294967295L => Some("\{v}U")
        _ => None
      }
    }
    "uint16" =>
      match parse_int64_str(s) {
        Some(v) if v >= 0L && v <= 65535L => Some("(\{v} : UInt16)")
        _ => None
      }
    "uint8" =>
      match parse_int64_str(s) {
        Some(v) if v >= 0L && v <= 255L => Some("b'\\x00' + (\{v}).to_byte()")
        _ => None
      }
    "int16" =>
      match parse_int64_str(s) {
        Some(v) if v >= -32768L && v <= 32767L => Some("Int16::from_int(\{v})")
        _ => None
      }
    _ =>
      // Int32
      match parse_int64_str(s) {
        Some(v) if v >= -2147483648L && v <= 2147483647L =>
          Some("(\{v} : Int32)")
        _ => None
      }
  }
}

///|
fn is_positive_int_text(raw : String) -> Bool {
  let s = raw.trim().to_owned()
  if s.is_empty() || s.has_prefix("-") {
    return false
  }
  let mut any_nz = false
  for ch in s {
    if ch == '+' {
      continue
    }
    if ch < '0' || ch > '9' {
      return false
    }
    if ch != '0' {
      any_nz = true
    }
  }
  any_nz
}

///|
fn emit_numeric_bound_checks(
  resolved : @ir.FieldType,
  wire : String,
  c : @spec.SchemaConstraints,
  checks : Array[String],
) -> Unit {
  match resolved {
    @ir.Prim(@ir.Int(fmt)) => {
      let use_native = fmt != "uint8"
      let zero_lit = match fmt {
        "int64" => "0L"
        "uint64" => "0UL"
        "uint32" => "0U"
        "uint16" => "(0 : UInt16)"
        "int16" => "Int16::from_int(0)"
        _ => "0"
      }
      let emit_cmp = (bound_opt : String?, op : String, label : String) => {
        match bound_opt {
          Some(bs) => {
            let exact_opt = if use_native {
              parse_exact_int_bound(bs, fmt)
            } else {
              None
            }
            match exact_opt {
              Some(ilit) =>
                checks.push(
                  "if __v \{op} \{ilit} { __errs.push(\{mbt_string_lit("field '" + wire + "' must be " + label + " " + bs)}) }",
                )
              None =>
                match
                  (
                    numeric_to_double_expr(resolved, "__v"),
                    normalize_double_lit(bs),
                  ) {
                  (Some(num_expr), Some((lit, _))) =>
                    checks.push(
                      "if (\{num_expr}) \{op} (\{lit} : Double) { __errs.push(\{mbt_string_lit("field '" + wire + "' must be " + label + " " + bs)}) }",
                    )
                  _ => ()
                }
            }
          }
          None => ()
        }
      }
      emit_cmp(c.minimum, "<", ">=")
      emit_cmp(c.exclusive_minimum, "<=", ">")
      emit_cmp(c.maximum, ">", "<=")
      emit_cmp(c.exclusive_maximum, ">=", "<")
      match c.multiple_of {
        Some(step_s) => {
          let step_opt = if use_native && is_positive_int_text(step_s) {
            parse_exact_int_bound(step_s, fmt)
          } else {
            None
          }
          match step_opt {
            Some(ilit) =>
              checks.push(
                "if __v % \{ilit} != \{zero_lit} { __errs.push(\{mbt_string_lit("field '" + wire + "' must be a multiple of " + step_s)}) }",
              )
            None =>
              match
                (
                  numeric_to_double_expr(resolved, "__v"),
                  normalize_double_lit(step_s),
                ) {
                (Some(num_expr), Some((lit, true))) =>
                  checks.push(
                    "let __q = (\{num_expr}) / (\{lit} : Double)\nlet __nearest = __q.round()\nif __q.is_nan() || __q.is_inf() || (__q - __nearest).abs() > 1.0e-12 * __nearest.abs().max(1.0) { __errs.push(\{mbt_string_lit("field '" + wire + "' must be a multiple of " + step_s)}) }",
                  )
                _ => ()
              }
          }
        }
        None => ()
      }
    }
    @ir.Prim(@ir.Num(_)) => {
      let emit_dbl = (bound_opt : String?, op : String, label : String) => {
        match bound_opt {
          Some(bs) =>
            match normalize_double_lit(bs) {
              Some((lit, _)) =>
                checks.push(
                  "if __v.is_nan() || __v \{op} (\{lit} : Double) { __errs.push(\{mbt_string_lit("field '" + wire + "' must be " + label + " " + bs)}) }",
                )
              None => ()
            }
          None => ()
        }
      }
      emit_dbl(c.minimum, "<", ">=")
      emit_dbl(c.exclusive_minimum, "<=", ">")
      emit_dbl(c.maximum, ">", "<=")
      emit_dbl(c.exclusive_maximum, ">=", "<")
      match c.multiple_of {
        Some(step_s) =>
          match normalize_double_lit(step_s) {
            Some((lit, true)) =>
              checks.push(
                "let __q = __v / (\{lit} : Double)\nlet __nearest = __q.round()\nif __q.is_nan() || __q.is_inf() || (__q - __nearest).abs() > 1.0e-12 * __nearest.abs().max(1.0) { __errs.push(\{mbt_string_lit("field '" + wire + "' must be a multiple of " + step_s)}) }",
              )
            _ => ()
          }
        None => ()
      }
    }
    _ => ()
  }
}

///|
fn GenContext::emit_record_validator(
  self : GenContext,
  type_name : String,
  r : @ir.RecordDef,
) -> @doc.Item {
  let lines : Array[String] = ["let __errs : Array[String] = []"]
  let mut used_self = false
  for f in r.fields {
    let c = f.constraints
    if c.is_empty() {
      continue
    }
    let resolved_raw = self.resolve_alias(f.type_)
    let (resolved, inner_optional) = match resolved_raw {
      @ir.Optional(inner) => (self.resolve_alias(inner), true)
      other => (other, false)
    }
    let has_prim_override = match resolved {
      @ir.Prim(p) => prim_override(p, self.cfg) is Some(_)
      _ => false
    }
    let checks : Array[String] = []
    if !has_prim_override {
      emit_numeric_bound_checks(resolved, f.wire, c, checks)
      if resolved is @ir.Prim(@ir.Str(fmt)) &&
        fmt != "uuid" &&
        fmt != "date-time" &&
        fmt != "binary" &&
        fmt != "bytes" &&
        fmt != "char" {
        match c.min_length {
          Some(n) =>
            checks.push(
              "if __v.char_length() < \{n} { __errs.push(\{mbt_string_lit("field '" + f.wire + "' length must be >= " + n.to_string())}) }",
            )
          None => ()
        }
        match c.max_length {
          Some(n) =>
            checks.push(
              "if __v.char_length() > \{n} { __errs.push(\{mbt_string_lit("field '" + f.wire + "' length must be <= " + n.to_string())}) }",
            )
          None => ()
        }
      }
    }
    match resolved {
      @ir.List(item_ty) => {
        match c.min_items {
          Some(n) =>
            checks.push(
              "if __v.length() < \{n} { __errs.push(\{mbt_string_lit("field '" + f.wire + "' must have at least " + n.to_string() + " items")}) }",
            )
          None => ()
        }
        match c.max_items {
          Some(n) =>
            checks.push(
              "if __v.length() > \{n} { __errs.push(\{mbt_string_lit("field '" + f.wire + "' must have at most " + n.to_string() + " items")}) }",
            )
          None => ()
        }
        if c.unique_items && field_type_can_eq(item_ty, self.cfg, self.can_eq) {
          checks.push(
            "let mut __dup = false\nfor __i in 0..<__v.length() {\n  for __j in (__i + 1)..<__v.length() {\n    if __v[__i] == __v[__j] {\n      __dup = true\n      break\n    }\n  }\n  if __dup { break }\n}\nif __dup { __errs.push(\{mbt_string_lit("field '" + f.wire + "' items must be unique")}) }",
          )
        }
      }
      @ir.MapTo(_) => {
        match c.min_properties {
          Some(n) =>
            checks.push(
              "if __v.length() < \{n} { __errs.push(\{mbt_string_lit("field '" + f.wire + "' must have at least " + n.to_string() + " entries")}) }",
            )
          None => ()
        }
        match c.max_properties {
          Some(n) =>
            checks.push(
              "if __v.length() > \{n} { __errs.push(\{mbt_string_lit("field '" + f.wire + "' must have at most " + n.to_string() + " entries")}) }",
            )
          None => ()
        }
      }
      _ => ()
    }
    if checks.is_empty() {
      continue
    }
    used_self = true
    let joined = checks.join("\n  ")
    let inner_body = if inner_optional {
      "match __v_opt {\n  Option::Some(__v) => {\n    \{joined}\n  }\n  Option::None => ()\n}"
    } else {
      joined
    }
    let bind_name = if inner_optional { "__v_opt" } else { "__v" }
    match f.presence {
      @ir.Required =>
        lines.push("{\n  let \{bind_name} = self.\{f.name}\n  \{inner_body}\n}")
      @ir.OptionalNullable if self.cfg.tri_state =>
        lines.push(
          "match self.\{f.name} {\n  NullableField::Value(\{bind_name}) => {\n    \{inner_body}\n  }\n  _ => ()\n}",
        )
      _ =>
        lines.push(
          "match self.\{f.name} {\n  Option::Some(\{bind_name}) => {\n    \{inner_body}\n  }\n  Option::None => ()\n}",
        )
    }
  }
  if !used_self {
    lines.push("ignore(self)")
  }
  lines.push("__errs")
  @doc.item(
    @doc.DocComment::new([
      "Validate OpenAPI schema constraints on this record. Returns an empty array when valid.",
      "Note: regex `pattern` constraints are documented on fields and not evaluated at runtime.",
    ]),
    @doc.Decl::Fn({
      self_type: Some(type_name),
      name: "validate",
      type_params: [],
      params: [@doc.FnParam::positional("self", @doc.Name(type_name))],
      return_type: Some(
        @doc.Applied(base=@doc.Name("Array"), args=[@doc.Name("String")]),
      ),
      is_async: false,
      error: @doc.NoRaise,
      vis: @doc.Pub,
      body: lines.join("\n"),
    }),
  )
}

///|
fn GenContext::emit_string_enum_def(
  self : GenContext,
  e : @ir.StringEnumDef,
  file : @doc.SourceFile,
) -> Unit {
  let type_name = self.type_name(e.name)
  let derives = self.derives_for(e.name)
  let variants : Array[@doc.EnumVariant] = []
  for v in e.variants {
    let vdoc = if v.wire == v.name {
      @doc.DocComment::empty()
    } else {
      @doc.DocComment::new(["Wire value: `\{v.wire}`."])
    }
    variants.push({ name: v.name, payload: [], doc: vdoc, })
  }
  match e.unknown_variant {
    Some(unk) =>
      variants.push({
        name: unk,
        payload: [(None, @doc.Name("String"))],
        doc: @doc.DocComment::new([
          "Forward-compatible fallback for unrecognized wire values.",
        ]),
      })
    None => ()
  }
  file.push(
    @doc.item_with_attrs(
      @doc.DocComment::new(e.docs),
      deprecated_attrs(e.deprecated),
      @doc.Decl::Enum({
        name: type_name,
        type_params: [],
        vis: @doc.PubAll,
        variants,
        derives,
        non_exhaustive: false,
      }),
    ),
  )
  // `to_wire` helper for parameter serialization and `ToJson`
  let wire_arms : Array[String] = []
  for v in e.variants {
    wire_arms.push("\{type_name}::\{v.name} => \{mbt_string_lit(v.wire)}")
  }
  match e.unknown_variant {
    Some(unk) => wire_arms.push("\{type_name}::\{unk}(raw) => raw")
    None => ()
  }
  file.push(
    @doc.item(
      @doc.DocComment::new(["Wire string representation of `\{type_name}`."]),
      @doc.Decl::Fn({
        self_type: Some(type_name),
        name: "to_wire",
        type_params: [],
        params: [@doc.FnParam::positional("self", @doc.Name(type_name))],
        return_type: Some(@doc.Name("String")),
        is_async: false,
        error: @doc.NoRaise,
        vis: @doc.Pub,
        body: "match self {\n" + wire_arms.join("\n") + "\n}",
      }),
    ),
  )
  // FromJson
  let from_arms : Array[String] = []
  for v in e.variants {
    from_arms.push("\{mbt_string_lit(v.wire)} => \{type_name}::\{v.name}")
  }
  match e.unknown_variant {
    Some(unk) => from_arms.push("other => \{type_name}::\{unk}(other)")
    None =>
      from_arms.push(
        "other => {\n  let err = r.error(\"unknown \{type_name} value: \" + other)\n  raise err\n}",
      )
  }
  let from_body = "let r = @rjson.JsonReader::new(json, path)\nmatch r.read_string() {\n" +
    from_arms.join("\n") +
    "\n}"
  file.push(make_from_json_impl(type_name, from_body))
  // ToJson
  for it in make_to_json_impl(type_name, "@rjson.write_string(self.to_wire())") {
    file.push(it)
  }
}

///|
fn GenContext::emit_tagged_enum_def(
  self : GenContext,
  u : @ir.TaggedEnumDef,
  file : @doc.SourceFile,
) -> Unit raise @doc.CodegenError {
  let type_name = self.type_name(u.name)
  let derives = self.derives_for(u.name)
  let variants : Array[@doc.EnumVariant] = []
  for v in u.variants {
    let payload : Array[(String?, @doc.TypeExpr)] = match v.payload {
      @ir.Unit => []
      @ir.NewType(ft) => {
        if !self.is_object_payload(ft) {
          raise @doc.CodegenError(
            "tagged union variant `\{type_name}::\{v.name}` has non-object NewType payload",
          )
        }
        [(None, self.field_type_expr(ft, in_model=true))]
      }
      @ir.Fields(fs) => {
        let out : Array[(String?, @doc.TypeExpr)] = []
        for f in fs {
          out.push((Some(f.name), self.struct_field_type(f, in_model=true)))
        }
        out
      }
    }
    variants.push({ name: v.name, payload, doc: @doc.DocComment::new(v.docs), })
  }
  match u.unknown_variant {
    Some(unk) =>
      variants.push({
        name: unk,
        payload: [(None, @doc.TypeExpr::qualified("cjson", "Json"))],
        doc: @doc.DocComment::new([
          "Fallback for unrecognized union tag values.",
        ]),
      })
    None => ()
  }
  file.push(
    @doc.item_with_attrs(
      @doc.DocComment::new(u.docs),
      deprecated_attrs(u.deprecated),
      @doc.Decl::Enum({
        name: type_name,
        type_params: [],
        vis: @doc.PubAll,
        variants,
        derives,
        non_exhaustive: false,
      }),
    ),
  )

  // FromJson (with hygienic reader name + MapTo tag exclusion)
  let tag_namer = @name.Namer::new()
  tag_namer.reserve("json")
  tag_namer.reserve("path")
  tag_namer.reserve("self")
  for v in u.variants {
    match v.payload {
      @ir.Fields(fs) =>
        for f in fs {
          tag_namer.reserve(f.name)
        }
      _ => ()
    }
  }
  let r_var = tag_namer.unique("__r")
  let obj_var = tag_namer.unique("__obj")
  let tag_prop_lit = mbt_string_lit(u.tag_property)
  let dec_arms : Array[String] = []
  for v in u.variants {
    let tag_lit = mbt_string_lit(v.wire_tag)
    match v.payload {
      @ir.Unit => dec_arms.push("\{tag_lit} => \{type_name}::\{v.name}")
      @ir.NewType(ft) => {
        let dec = match self.resolve_alias(ft) {
          @ir.MapTo(inner) => {
            let inner_dec = self.emit_decode_expr(
              inner,
              "__mv_0",
              in_model=true,
              depth=1,
            )
            "\{r_var}.read_map_excluding(\{tag_prop_lit}, __mv_0 => \{inner_dec})"
          }
          _ => self.emit_decode_expr(ft, r_var, in_model=true)
        }
        dec_arms.push("\{tag_lit} => \{type_name}::\{v.name}(\{dec})")
      }
      @ir.Fields(fs) =>
        if fs.is_empty() {
          dec_arms.push("\{tag_lit} => \{type_name}::\{v.name}")
        } else {
          let stmts : Array[String] = []
          for f in fs {
            stmts.push(self.emit_field_decode_stmt(f, r_var))
          }
          let args = fs.map(f => "\{f.name}~").join(", ")
          stmts.push("\{type_name}::\{v.name}(\{args})")
          dec_arms.push("\{tag_lit} => {\n" + stmts.join("\n") + "\n}")
        }
    }
  }
  match u.unknown_variant {
    Some(unk) => dec_arms.push("_ => \{type_name}::\{unk}(\{r_var}.raw())")
    None =>
      dec_arms.push(
        "other => {\n  let __err = \{r_var}.error(\"unknown \{type_name} tag: \" + other)\n  raise __err\n}",
      )
  }
  let from_body = "let \{r_var} = @rjson.JsonReader::new(json, path)\nmatch \{r_var}.field(\{tag_prop_lit}).read_string() {\n" +
    dec_arms.join("\n") +
    "\n}"
  file.push(make_from_json_impl(type_name, from_body))

  // ToJson
  let enc_arms : Array[String] = []
  for v in u.variants {
    let tag_lit = mbt_string_lit(v.wire_tag)
    match v.payload {
      @ir.Unit =>
        enc_arms.push(
          "\{type_name}::\{v.name} => @rjson.ObjectBuilder::new().field(\{tag_prop_lit}, @rjson.write_string(\{tag_lit})).build()",
        )
      @ir.NewType(ft) => {
        let enc = self.emit_encode_expr(ft, "__payload", in_model=true)
        enc_arms.push(
          "\{type_name}::\{v.name}(__payload) => @rjson.ObjectBuilder::new().merge_object(\{enc}).field(\{tag_prop_lit}, @rjson.write_string(\{tag_lit})).build()",
        )
      }
      @ir.Fields(fs) =>
        if fs.is_empty() {
          enc_arms.push(
            "\{type_name}::\{v.name} => @rjson.ObjectBuilder::new().field(\{tag_prop_lit}, @rjson.write_string(\{tag_lit})).build()",
          )
        } else {
          let pat_args = fs.map(f => "\{f.name}~").join(", ")
          let lines : Array[String] = [
            "let \{obj_var} = @rjson.ObjectBuilder::new().field(\{tag_prop_lit}, @rjson.write_string(\{tag_lit}))",
          ]
          for f in fs {
            if f.wire == u.tag_property {
              lines.push("ignore(\{f.name})")
              continue
            }
            lines.push(self.emit_field_encode_call(f, f.name, obj_var~))
          }
          lines.push("\{obj_var}.build()")
          enc_arms.push(
            "\{type_name}::\{v.name}(\{pat_args}) => {\n" +
            lines.join("\n") +
            "\n}",
          )
        }
    }
  }
  match u.unknown_variant {
    Some(unk) => enc_arms.push("\{type_name}::\{unk}(raw) => raw")
    None => ()
  }
  let to_body = "match self {\n" + enc_arms.join("\n") + "\n}"
  for it in make_to_json_impl(type_name, to_body) {
    file.push(it)
  }
}

///|
fn GenContext::emit_untagged_enum_def(
  self : GenContext,
  u : @ir.UntaggedEnumDef,
  file : @doc.SourceFile,
) -> Unit {
  let type_name = self.type_name(u.name)
  let derives = self.derives_for(u.name)
  let variants : Array[@doc.EnumVariant] = []
  for v in u.variants {
    variants.push({
      name: v.name,
      payload: [(None, self.field_type_expr(v.type_, in_model=true))],
      doc: @doc.DocComment::empty(),
    })
  }
  file.push(
    @doc.item_with_attrs(
      @doc.DocComment::new(u.docs),
      deprecated_attrs(u.deprecated),
      @doc.Decl::Enum({
        name: type_name,
        type_params: [],
        vis: @doc.PubAll,
        variants,
        derives,
        non_exhaustive: false,
      }),
    ),
  )
  // FromJson: try all fallible variants first, then infallible catch-all variants last
  // so a catch-all (`JsonValue`) declared early never shadows typed variants.
  let lines : Array[String] = ["let __r = @rjson.JsonReader::new(json, path)"]
  let fallible : Array[@ir.UntaggedVariantIR] = []
  let infallible : Array[@ir.UntaggedVariantIR] = []
  for v in u.variants {
    if self.decode_is_infallible(v.type_) {
      infallible.push(v)
    } else {
      fallible.push(v)
    }
  }
  for v in fallible {
    let dec = self.emit_decode_expr(v.type_, "__r", in_model=true)
    lines.push(
      "try { return \{type_name}::\{v.name}(\{dec}) } catch { _ => () }",
    )
  }
  match infallible {
    [first, ..] => {
      let dec = self.emit_decode_expr(first.type_, "__r", in_model=true)
      lines.push("return \{type_name}::\{first.name}(\{dec})")
    }
    [] => {
      lines.push(
        "let __err = __r.error(\"no matching variant for \{type_name}\")",
      )
      lines.push("raise __err")
    }
  }
  file.push(make_from_json_impl(type_name, lines.join("\n")))
  // ToJson
  let enc_arms : Array[String] = []
  for v in u.variants {
    let enc = self.emit_encode_expr(v.type_, "val", in_model=true)
    enc_arms.push("\{type_name}::\{v.name}(val) => \{enc}")
  }
  for
    it in make_to_json_impl(
      type_name,
      "match self {\n" + enc_arms.join("\n") + "\n}",
    ) {
    file.push(it)
  }
}

///|
fn GenContext::emit_alias_def(
  self : GenContext,
  a : @ir.AliasDef,
  file : @doc.SourceFile,
) -> Unit {
  let type_name = self.type_name(a.name)
  file.push(
    @doc.item_with_attrs(
      @doc.DocComment::new(a.docs),
      deprecated_attrs(a.deprecated),
      @doc.Decl::Alias({
        name: type_name,
        type_params: [],
        target: self.field_type_expr(a.target, in_model=true),
        vis: @doc.Pub,
      }),
    ),
  )
}

///|
fn collect_named_refs(ft : @ir.FieldType, out : Array[String]) -> Unit {
  match ft {
    @ir.Named(name) => out.push(name)
    @ir.List(inner) | @ir.MapTo(inner) | @ir.Optional(inner) =>
      collect_named_refs(inner, out)
    @ir.Prim(_) | @ir.JsonValue => ()
  }
}

///|
fn collect_def_refs(def : @ir.TypeDef) -> Array[String] {
  let out : Array[String] = []
  match def {
    @ir.Record(r) =>
      for f in r.fields {
        collect_named_refs(f.type_, out)
      }
    @ir.TaggedEnum(u) =>
      for v in u.variants {
        match v.payload {
          @ir.Unit => ()
          @ir.NewType(ft) => collect_named_refs(ft, out)
          @ir.Fields(fs) =>
            for f in fs {
              collect_named_refs(f.type_, out)
            }
        }
      }
    @ir.StringEnum(_) => ()
    @ir.UntaggedEnum(u) =>
      for v in u.variants {
        collect_named_refs(v.type_, out)
      }
    @ir.Alias(a) => collect_named_refs(a.target, out)
  }
  out
}

///|
fn collect_op_root_refs(op : @ir.OpIR, out : Array[String]) -> Unit {
  for p in op.params {
    collect_named_refs(p.type_, out)
  }
  match op.body {
    @ir.Json(ft, ..) => collect_named_refs(ft, out)
    @ir.Multipart(parts, ..) | @ir.FormUrlEncoded(parts, ..) =>
      for part in parts {
        if !part.is_binary {
          collect_named_refs(part.type_, out)
        }
      }
    @ir.Text(..) | @ir.Binary(..) | @ir.NoBody => ()
  }
  for resp in op.responses {
    match resp.body_kind {
      @ir.Json(ft) | @ir.Other(Some(ft)) | @ir.Stream(@ir.Ndjson(ft)) =>
        collect_named_refs(ft, out)
      _ => ()
    }
    for h in resp.headers {
      collect_named_refs(h.type_, out)
    }
  }
}

///|
/// Classify every model `TypeDef` by transitive operation-group ownership:
/// schemas reachable from exactly 1 operation group live in `model/.mbt`;
/// schemas shared across 2+ groups (or unreferenced by operations) live in
/// `model/shared.mbt`.
fn GenContext::classify_models_by_group(
  self : GenContext,
) -> Array[(String, Array[@ir.TypeDef])] {
  let defs = self.ir.defs()
  let dep_graph : Map[String, Array[String]] = Map([])
  for d in defs {
    dep_graph[d.name()] = collect_def_refs(d)
  }

  // Allocate collision-free file stems per operation group (reserving shared/types/tri_state).
  let stem_namer = @name.Namer::new()
  stem_namer.reserve("shared")
  stem_namer.reserve("types")
  stem_namer.reserve("tri_state")
  let group_stems : Array[(String, Array[@ir.OpIR])] = []
  for entry in self.groups {
    let (group_name, ops) = entry
    let raw_stem = if group_name == "" {
      "core"
    } else {
      @name.ident_snake(group_name)
    }
    let stem = stem_namer.unique(raw_stem)
    group_stems.push((stem, ops))
  }

  // Compute transitive closure per group and count how many groups reach each schema.
  let owner_count : Map[String, Int32] = Map([])
  let single_owner : Map[String, String] = Map([])
  for entry in group_stems {
    let (stem, ops) = entry
    let seeds : Array[String] = []
    for op in ops {
      collect_op_root_refs(op, seeds)
    }
    let visited : Map[String, Bool] = Map([])
    let stack : Array[String] = []
    for s in seeds {
      if dep_graph.contains(s) && !visited.contains(s) {
        visited[s] = true
        stack.push(s)
      }
    }
    while !stack.is_empty() {
      let cur = stack.pop().unwrap()
      match dep_graph.get(cur) {
        Some(children) =>
          for ch in children {
            if dep_graph.contains(ch) && !visited.contains(ch) {
              visited[ch] = true
              stack.push(ch)
            }
          }
        None => ()
      }
    }
    for name, _ in visited {
      let prev = owner_count.get(name).unwrap_or(0)
      owner_count[name] = prev + 1
      if prev == 0 {
        single_owner[name] = stem
      }
    }
  }

  let shared_defs : Array[@ir.TypeDef] = []
  let per_group : Map[String, Array[@ir.TypeDef]] = Map([])
  for entry in group_stems {
    per_group[entry.0] = []
  }
  for d in defs {
    let name = d.name()
    if owner_count.get(name).unwrap_or(0) == 1 {
      match single_owner.get(name) {
        Some(stem) =>
          match per_group.get(stem) {
            Some(arr) => arr.push(d)
            None => shared_defs.push(d)
          }
        None => shared_defs.push(d)
      }
    } else {
      shared_defs.push(d)
    }
  }

  let out : Array[(String, Array[@ir.TypeDef])] = []
  if !shared_defs.is_empty() {
    out.push(("shared", shared_defs))
  }
  for entry in group_stems {
    let stem = entry.0
    match per_group.get(stem) {
      Some(arr) if !arr.is_empty() => out.push((stem, arr))
      _ => ()
    }
  }
  out
}

///|
/// Emit all `model/*.mbt` files (plus optional `model/tri_state.mbt` when
/// `cfg.tri_state == true`).
/// Above `cfg.model_split_threshold`, splits models semantically by operation
/// group (`model/shared.mbt` + `model/.mbt`) inside the single `model/`
/// package.
fn GenContext::emit_model_files(
  self : GenContext,
) -> Array[GeneratedFile] raise @doc.CodegenError {
  let out : Array[GeneratedFile] = []
  if self.cfg.tri_state {
    let ts_file = @doc.SourceFile::with_header(self.header_lines())
    ts_file.push(
      @doc.enum_item(
        @doc.DocComment::new([
          "Tri-state field wrapper distinguishing absent (`Absent`), explicit JSON `null` (`Null`), and a present value (`Value`).",
        ]),
        {
          name: "NullableField",
          type_params: ["T"],
          vis: @doc.PubAll,
          variants: [
            { name: "Absent", payload: [], doc: @doc.DocComment::empty(), },
            { name: "Null", payload: [], doc: @doc.DocComment::empty(), },
            {
              name: "Value",
              payload: [(None, @doc.Name("T"))],
              doc: @doc.DocComment::empty(),
            },
          ],
          derives: ["Debug", "Eq", "Compare"],
          non_exhaustive: false,
        },
      ),
    )
    out.push({
      path: "model/tri_state.mbt",
      content: @fmt.render_file(ts_file),
    })
  }
  let defs = self.ir.defs()
  if defs.is_empty() {
    let empty_file = @doc.SourceFile::with_header(self.header_lines())
    out.push({ path: "model/types.mbt", content: @fmt.render_file(empty_file), })
    return out
  }
  let should_split = self.cfg.model_split_threshold > 0 &&
    defs.length() > self.cfg.model_split_threshold
  if !should_split {
    let file = @doc.SourceFile::with_header(self.header_lines())
    for d in defs {
      self.emit_type_def(d, file)
    }
    out.push({ path: "model/types.mbt", content: @fmt.render_file(file), })
  } else {
    let max_group_defs : Int32 = 100
    let shard_size : Int32 = 80
    let groups = self.classify_models_by_group()
    let file_namer = @name.Namer::new()
    let _ = file_namer.unique("tri_state")
    let _ = file_namer.unique("types")
    // Reserve all non-sharded group stems first so shard names never collide.
    let reserved_stems : Array[String] = []
    for pair in groups {
      let (stem, group_defs) = pair
      if group_defs.length() <= max_group_defs {
        reserved_stems.push(file_namer.unique(stem))
      } else {
        reserved_stems.push(stem)
      }
    }
    for idx in 0.. Unit raise @doc.CodegenError {
  match def {
    @ir.Record(r) => self.emit_record_def(r, file)
    @ir.StringEnum(e) => self.emit_string_enum_def(e, file)
    @ir.TaggedEnum(u) => self.emit_tagged_enum_def(u, file)
    @ir.UntaggedEnum(u) => self.emit_untagged_enum_def(u, file)
    @ir.Alias(a) => self.emit_alias_def(a, file)
  }
}