// Generator output model, deterministic spec hashing, fixed-point trait
// analysis (`Eq` / `Compare`), name collision checks, and shared `GenContext`.

///|
/// One emitted file in a generated MoonBit client module.
#derive(Debug, Eq)
pub(all) struct GeneratedFile {
  /// Relative POSIX path inside the target module directory (e.g. `"model/types.mbt"`).
  path : String
  /// Full UTF-8 text content of the file.
  content : String
}

///|
/// Complete deterministic output of a generation run.
#derive(Debug, Eq)
pub(all) struct GeneratedProject {
  /// All emitted files, sorted lexicographically by `path`.
  files : Array[GeneratedFile]
  /// Sorted manifest of owned generated paths (mirrors `.openapi-moonbit-manifest`).
  manifest : Array[String]
  /// Deterministic SHA-256 hex digest of the raw input OpenAPI specification.
  spec_hash : String
}

///|
/// Compute the deterministic lowercase SHA-256 hex digest of `raw_spec`.
pub fn compute_spec_hash(raw_spec : String) -> String {
  let bytes = @utf8.encode(raw_spec)
  @crypto.bytes_to_hex_string(@crypto.sha256(bytes))
}

///|
/// Internal generation context computed once per `IrModel` + `GeneratorConfig`.
priv struct GenContext {
  ir : @ir.IrModel
  cfg : @config.GeneratorConfig
  spec_hash : String
  /// Filtered operations (excluding `cfg.ignored_paths`).
  operations : Array[@ir.OpIR]
  /// Filtered tag groups in deterministic order.
  groups : Array[(String, Array[@ir.OpIR])]
  /// Validated model type names (`ir_name -> final_name`).
  resolved_type_names : Map[String, String]
  /// Validated operation method names (`" " -> final_name`).
  resolved_op_names : Map[String, String]
  /// Name/config validation errors raised at the start of `generate()`.
  validation_errors : Array[String]
  /// True if the OpenAPI spec declares any security schemes or non-empty operation security.
  spec_declares_security : Bool
  /// Type-level trait eligibility computed by optimistic fixed point.
  can_eq : Map[String, Bool]
  can_compare : Map[String, Bool]
  /// Package dependency usage flags (computed precisely to avoid unused imports).
  model_uses_uuid : Bool
  model_uses_time : Bool
  model_uses_rjson : Bool
  model_uses_cjson : Bool
  client_uses_model : Bool
  client_uses_uuid : Bool
  client_uses_time : Bool
  client_uses_ws : Bool
  client_uses_stream : Bool
  client_uses_path_params : Bool
  client_uses_send_request : Bool
  client_uses_api_error : Bool
  client_uses_decode_json : Bool
}

///|
fn op_key(op : @ir.OpIR) -> String {
  op.http_method.to_wire() + " " + op.path
}

///|
fn GenContext::validate(self : GenContext) -> Unit raise @doc.CodegenError {
  if !self.validation_errors.is_empty() {
    raise @doc.CodegenError(self.validation_errors.join("; "))
  }
}

///|
fn GenContext::header_lines(self : GenContext) -> Array[String] {
  let out : Array[String] = []
  for raw_line in self.cfg.license_header {
    for part in raw_line.split("\n") {
      let clean = if part.has_suffix("\r") {
        part[:part.length() - 1].to_owned()
      } else {
        part.to_owned()
      }
      out.push(clean)
    }
  }
  out.push("Generated by openapi-moonbit — DO NOT EDIT")
  out.push("Spec SHA-256: \{self.spec_hash}")
  out
}

///|
fn GenContext::type_name(self : GenContext, ir_name : String) -> String {
  self.resolved_type_names
  .get(ir_name)
  .unwrap_or(self.cfg.resolve_type_name(ir_name))
}

///|
fn GenContext::op_method_name(self : GenContext, op : @ir.OpIR) -> String {
  self.resolved_op_names
  .get(op_key(op))
  .unwrap_or(self.cfg.resolve_operation_name(op.operation_id, op.method_name))
}

///|
/// Follow `Alias` chains up to 32 hops to discover the underlying semantic type.
fn GenContext::resolve_alias(
  self : GenContext,
  ft : @ir.FieldType,
) -> @ir.FieldType {
  resolve_alias_in_ir(self.ir, ft)
}

///|
fn resolve_alias_in_ir(ir : @ir.IrModel, ft : @ir.FieldType) -> @ir.FieldType {
  let mut cur = ft
  for _ in 0..<32 {
    match cur {
      @ir.Named(name) =>
        match ir.def(name) {
          Some(@ir.Alias(alias_def)) => cur = alias_def.target
          _ => return cur
        }
      _ => return cur
    }
  }
  cur
}

///|
fn GenContext::decode_is_infallible(
  self : GenContext,
  ft : @ir.FieldType,
) -> Bool {
  match self.resolve_alias(ft) {
    @ir.JsonValue => true
    @ir.Optional(inner) => self.decode_is_infallible(inner)
    _ => false
  }
}

///|
fn GenContext::is_object_payload(self : GenContext, ft : @ir.FieldType) -> Bool {
  match self.resolve_alias(ft) {
    @ir.MapTo(_) | @ir.JsonValue => true
    @ir.Named(name) =>
      match self.ir.def(name) {
        Some(@ir.Record(_)) | Some(@ir.TaggedEnum(_)) => true
        _ => false
      }
    _ => false
  }
}

///|
fn override_can_eq(target : String) -> Bool {
  match target {
    "String"
    | "Int32"
    | "Int64"
    | "UInt32"
    | "UInt64"
    | "Int16"
    | "UInt16"
    | "Byte"
    | "Double"
    | "Bool"
    | "Char"
    | "Bytes"
    | "@uuid.UUID"
    | "@rjson.DateTime" => true
    _ => false
  }
}

///|
fn override_can_compare(target : String) -> Bool {
  override_can_eq(target)
}

///|
fn prim_format(prim : @ir.Prim) -> String {
  match prim {
    @ir.Str(fmt) | @ir.Int(fmt) | @ir.Num(fmt) => fmt
    @ir.Bool => ""
  }
}

///|
fn prim_override(prim : @ir.Prim, cfg : @config.GeneratorConfig) -> String? {
  let fmt = prim_format(prim)
  if fmt.is_empty() {
    None
  } else {
    cfg.format_override(fmt)
  }
}

///|
/// Whether `prim` directly uses `@uuid.UUID`, `@time.ZonedDateTime`, or
/// `@rjson.DateTime` given `cfg.format_overrides`.
fn prim_uses_uuid(prim : @ir.Prim, cfg : @config.GeneratorConfig) -> Bool {
  match prim_override(prim, cfg) {
    Some(target) => target == "@uuid.UUID"
    None => prim is @ir.Str("uuid")
  }
}

///|
fn prim_uses_time(prim : @ir.Prim, cfg : @config.GeneratorConfig) -> Bool {
  match prim_override(prim, cfg) {
    Some(target) => target == "@time.ZonedDateTime"
    None => false
  }
}

///|
fn prim_uses_rjson_datetime(
  prim : @ir.Prim,
  cfg : @config.GeneratorConfig,
) -> Bool {
  match prim_override(prim, cfg) {
    Some(target) => target == "@rjson.DateTime"
    None => prim is @ir.Str("date-time")
  }
}

///|
fn field_type_can_eq(
  ft : @ir.FieldType,
  cfg : @config.GeneratorConfig,
  can_eq : Map[String, Bool],
) -> Bool {
  match ft {
    @ir.Prim(p) =>
      match prim_override(p, cfg) {
        Some(target) => override_can_eq(target)
        None => true
      }
    @ir.Named(name) => can_eq.get(name).unwrap_or(true)
    @ir.List(inner) | @ir.MapTo(inner) | @ir.Optional(inner) =>
      field_type_can_eq(inner, cfg, can_eq)
    @ir.JsonValue => true
  }
}

///|
fn field_type_can_compare(
  ft : @ir.FieldType,
  cfg : @config.GeneratorConfig,
  can_compare : Map[String, Bool],
) -> Bool {
  match ft {
    @ir.Prim(p) =>
      match prim_override(p, cfg) {
        Some(target) => override_can_compare(target)
        None => true
      }
    @ir.Named(name) => can_compare.get(name).unwrap_or(true)
    @ir.List(inner) | @ir.Optional(inner) =>
      field_type_can_compare(inner, cfg, can_compare)
    // `Map[String, T]` and `@cjson.Json` do not implement `Compare`.
    @ir.MapTo(_) | @ir.JsonValue => false
  }
}

///|
fn def_can_eq(
  def : @ir.TypeDef,
  cfg : @config.GeneratorConfig,
  can_eq : Map[String, Bool],
) -> Bool {
  match def {
    @ir.Record(r) => {
      for f in r.fields {
        if !field_type_can_eq(f.type_, cfg, can_eq) {
          return false
        }
      }
      true
    }
    @ir.TaggedEnum(u) => {
      for v in u.variants {
        match v.payload {
          @ir.Unit => ()
          @ir.NewType(ft) =>
            if !field_type_can_eq(ft, cfg, can_eq) {
              return false
            }
          @ir.Fields(fs) =>
            for f in fs {
              if !field_type_can_eq(f.type_, cfg, can_eq) {
                return false
              }
            }
        }
      }
      true
    }
    @ir.StringEnum(_) => true
    @ir.UntaggedEnum(u) => {
      for v in u.variants {
        if !field_type_can_eq(v.type_, cfg, can_eq) {
          return false
        }
      }
      true
    }
    @ir.Alias(a) => field_type_can_eq(a.target, cfg, can_eq)
  }
}

///|
fn def_can_compare(
  def : @ir.TypeDef,
  cfg : @config.GeneratorConfig,
  can_compare : Map[String, Bool],
) -> Bool {
  match def {
    @ir.Record(r) => {
      for f in r.fields {
        if !field_type_can_compare(f.type_, cfg, can_compare) {
          return false
        }
      }
      true
    }
    @ir.TaggedEnum(u) => {
      if u.open {
        // Open fallback carries `@cjson.Json`, which does not implement `Compare`.
        return false
      }
      for v in u.variants {
        match v.payload {
          @ir.Unit => ()
          @ir.NewType(ft) =>
            if !field_type_can_compare(ft, cfg, can_compare) {
              return false
            }
          @ir.Fields(fs) =>
            for f in fs {
              if !field_type_can_compare(f.type_, cfg, can_compare) {
                return false
              }
            }
        }
      }
      true
    }
    @ir.StringEnum(_) => true
    @ir.UntaggedEnum(u) => {
      for v in u.variants {
        if !field_type_can_compare(v.type_, cfg, can_compare) {
          return false
        }
      }
      true
    }
    @ir.Alias(a) => field_type_can_compare(a.target, cfg, can_compare)
  }
}

///|
fn compute_trait_eligibility(
  ir : @ir.IrModel,
  cfg : @config.GeneratorConfig,
) -> (Map[String, Bool], Map[String, Bool]) {
  let defs = ir.defs()
  let can_eq : Map[String, Bool] = Map([])
  let can_compare : Map[String, Bool] = Map([])
  for d in defs {
    can_eq[d.name()] = true
    can_compare[d.name()] = true
  }
  // Optimistic fixed point handles mutually recursive types accurately.
  let mut changed = true
  while changed {
    changed = false
    for d in defs {
      let name = d.name()
      if can_eq.get(name).unwrap_or(false) && !def_can_eq(d, cfg, can_eq) {
        can_eq[name] = false
        changed = true
      }
      if can_compare.get(name).unwrap_or(false) &&
        !def_can_compare(d, cfg, can_compare) {
        can_compare[name] = false
        changed = true
      }
    }
  }
  (can_eq, can_compare)
}

///|
fn scan_ft_usage(
  ft : @ir.FieldType,
  cfg : @config.GeneratorConfig,
  uses_uuid : Ref[Bool],
  uses_time : Ref[Bool],
  uses_model : Ref[Bool],
  uses_cjson : Ref[Bool],
  uses_rjson : Ref[Bool],
) -> Unit {
  match ft {
    @ir.Prim(p) => {
      if prim_uses_uuid(p, cfg) {
        uses_uuid.val = true
      }
      if prim_uses_time(p, cfg) {
        uses_time.val = true
      }
      if prim_uses_rjson_datetime(p, cfg) {
        uses_rjson.val = true
      }
    }
    @ir.Named(_) => uses_model.val = true
    @ir.List(inner) | @ir.MapTo(inner) | @ir.Optional(inner) =>
      scan_ft_usage(
        inner, cfg, uses_uuid, uses_time, uses_model, uses_cjson, uses_rjson,
      )
    @ir.JsonValue => uses_cjson.val = true
  }
}

///|
/// Scan decoded types recursively for resolved `uuid` (which emits `@uuid.from_hex`).
fn scan_decoded_uuid(
  ir : @ir.IrModel,
  ft : @ir.FieldType,
  cfg : @config.GeneratorConfig,
  uses_uuid : Ref[Bool],
) -> Unit {
  let resolved = resolve_alias_in_ir(ir, ft)
  match resolved {
    @ir.Prim(p) => if prim_uses_uuid(p, cfg) { uses_uuid.val = true }
    @ir.List(inner) | @ir.MapTo(inner) | @ir.Optional(inner) =>
      scan_decoded_uuid(ir, inner, cfg, uses_uuid)
    _ => ()
  }
}

///|
fn is_ws_operation(op : @ir.OpIR) -> Bool {
  for resp in op.responses {
    if resp.status is @spec.Code(101) {
      return true
    }
  }
  false
}

///|
/// True when a non-WebSocket operation declares at least one success or
/// fallback `default` streaming response and should therefore route through
/// `StreamingTransport`.
fn is_streaming_operation(op : @ir.OpIR) -> Bool {
  if is_ws_operation(op) {
    return false
  }
  let has_explicit_success = op.responses
    .iter()
    .any(r => is_success_status(r.status))
  for resp in op.responses {
    let include_as_success = is_success_status(resp.status) ||
      (!has_explicit_success && resp.status is @spec.Default)
    if include_as_success && resp.body_kind is @ir.Stream(_) {
      return true
    }
  }
  false
}

///|
fn response_decodes_json_helper(
  ir : @ir.IrModel,
  cfg : @config.GeneratorConfig,
  resp : @ir.ResponseIR,
) -> Bool {
  match resp.body_kind {
    @ir.Json(ft) => !(resolve_alias_in_ir(ir, ft) is @ir.JsonValue)
    @ir.Other(Some(ft)) => {
      let resolved = resolve_alias_in_ir(ir, ft)
      match resolved {
        @ir.Prim(@ir.Str(fmt)) if (fmt == "binary" || fmt == "bytes") &&
          cfg.format_override(fmt) is None => false
        @ir.Prim(@ir.Str("")) => false
        @ir.JsonValue => false
        _ => true
      }
    }
    _ => false
  }
}

///|
fn GenContext::new(
  raw_spec : String,
  ir : @ir.IrModel,
  cfg : @config.GeneratorConfig,
) -> GenContext {
  let spec_hash = compute_spec_hash(raw_spec)
  let (can_eq, can_compare) = compute_trait_eligibility(ir, cfg)
  let validation_errors : Array[String] = []
  cfg.validate() catch {
    @config.InvalidYaml(msg) => validation_errors.push(msg)
    @config.InvalidField(field~, message~) =>
      validation_errors.push("\{field}: \{message}")
  }

  // Validate and resolve model type names (detect type_renames and NullableField collisions)
  let resolved_type_names : Map[String, String] = Map([])
  let used_type_names : Map[String, String] = Map([])
  let type_namer = @name.Namer::new()
  type_namer.reserve_builtin_types()
  if cfg.tri_state {
    type_namer.reserve("NullableField")
  }
  for def in ir.defs() {
    let ir_name = def.name()
    let explicit_rename = cfg.type_renames.get(ir_name)
    match explicit_rename {
      Some(target) => {
        if cfg.tri_state && target == "NullableField" {
          validation_errors.push(
            "type_renames maps '\{ir_name}' to reserved tri-state type 'NullableField'",
          )
        }
        match used_type_names.get(target) {
          Some(prev) =>
            validation_errors.push(
              "duplicate model type name '\{target}' (from '\{prev}' and '\{ir_name}')",
            )
          None => ()
        }
        type_namer.reserve(target)
        used_type_names[target] = ir_name
        resolved_type_names[ir_name] = target
      }
      None => {
        let final_name = if cfg.tri_state && ir_name == "NullableField" {
          type_namer.unique_type(ir_name)
        } else {
          match used_type_names.get(ir_name) {
            Some(prev) => {
              validation_errors.push(
                "model type name '\{ir_name}' collides with rename target from '\{prev}'",
              )
              type_namer.unique_type(ir_name)
            }
            None => {
              type_namer.reserve(ir_name)
              ir_name
            }
          }
        }
        used_type_names[final_name] = ir_name
        resolved_type_names[ir_name] = final_name
      }
    }
  }

  // Detect upfront whether any non-ignored operation streams so `new_streaming`
  // is reserved in `op_namer` without affecting non-streaming specs.
  let mut any_stream_op = false
  for op in ir.operations() {
    if cfg.is_path_ignored(op.path) {
      continue
    }
    if is_streaming_operation(op) {
      any_stream_op = true
      break
    }
  }

  // Filter operations and allocate collision-free method names reserving built-in Client methods
  let operations : Array[@ir.OpIR] = []
  let group_map : Map[String, Array[@ir.OpIR]] = Map([])
  let group_order : Array[String] = []
  let op_namer = @name.Namer::new()
  op_namer.reserve("new")
  op_namer.reserve("with_config")
  op_namer.reserve("with_auth")
  op_namer.reserve("with_base_url")
  op_namer.reserve("config")
  op_namer.reserve("prepare_request")
  op_namer.reserve("expand_op_path")
  op_namer.reserve("send_request")
  op_namer.reserve("send_stream_request")
  op_namer.reserve("decode_json_response")
  op_namer.reserve("api_error_from_response")
  op_namer.reserve("api_error_from_stream_response")
  if any_stream_op {
    op_namer.reserve("new_streaming")
  }
  let resolved_op_names : Map[String, String] = Map([])
  let explicit_op_targets : Map[String, String] = Map([])
  let mut spec_declares_security = !ir.security_schemes().is_empty()

  for op in ir.operations() {
    if !op.security.is_empty() {
      spec_declares_security = true
    }
    if cfg.is_path_ignored(op.path) {
      continue
    }
    operations.push(op)
    let key = op_key(op)
    let final_method = match cfg.operation_renames.get(op.operation_id) {
      Some(target) => {
        if target == "new" ||
          target == "with_config" ||
          target == "with_auth" ||
          target == "with_base_url" ||
          target == "config" ||
          target == "prepare_request" ||
          target == "expand_op_path" ||
          target == "send_request" ||
          target == "send_stream_request" ||
          target == "decode_json_response" ||
          target == "api_error_from_response" ||
          target == "api_error_from_stream_response" ||
          (any_stream_op && target == "new_streaming") {
          validation_errors.push(
            "operation_renames maps '\{op.operation_id}' to reserved Client method '\{target}'",
          )
        }
        match explicit_op_targets.get(target) {
          Some(prev) =>
            validation_errors.push(
              "duplicate operation_renames target '\{target}' (for '\{prev}' and '\{op.operation_id}')",
            )
          None => explicit_op_targets[target] = op.operation_id
        }
        op_namer.unique(target)
      }
      None => op_namer.unique(op.method_name)
    }
    resolved_op_names[key] = final_method

    match group_map.get(op.group) {
      Some(list) => list.push(op)
      None => {
        group_order.push(op.group)
        group_map[op.group] = [op]
      }
    }
  }
  let groups : Array[(String, Array[@ir.OpIR])] = []
  for g in group_order {
    match group_map.get(g) {
      Some(ops) => groups.push((g, ops))
      None => ()
    }
  }

  let m_uuid : Ref[Bool] = { val: false, }
  let m_time : Ref[Bool] = { val: false, }
  let m_dummy : Ref[Bool] = { val: false, }
  let m_cjson : Ref[Bool] = { val: false, }
  let m_rjson : Ref[Bool] = { val: false, }
  let mut m_has_non_alias = false
  for def in ir.defs() {
    match def {
      @ir.Record(r) => {
        m_has_non_alias = true
        for f in r.fields {
          scan_ft_usage(f.type_, cfg, m_uuid, m_time, m_dummy, m_cjson, m_rjson)
          scan_decoded_uuid(ir, f.type_, cfg, m_uuid)
        }
      }
      @ir.TaggedEnum(u) => {
        m_has_non_alias = true
        for v in u.variants {
          match v.payload {
            @ir.Unit => ()
            @ir.NewType(ft) => {
              scan_ft_usage(ft, cfg, m_uuid, m_time, m_dummy, m_cjson, m_rjson)
              scan_decoded_uuid(ir, ft, cfg, m_uuid)
            }
            @ir.Fields(fs) =>
              for f in fs {
                scan_ft_usage(
                  f.type_,
                  cfg,
                  m_uuid,
                  m_time,
                  m_dummy,
                  m_cjson,
                  m_rjson,
                )
                scan_decoded_uuid(ir, f.type_, cfg, m_uuid)
              }
          }
        }
      }
      @ir.StringEnum(_) => m_has_non_alias = true
      @ir.UntaggedEnum(u) => {
        m_has_non_alias = true
        for v in u.variants {
          scan_ft_usage(v.type_, cfg, m_uuid, m_time, m_dummy, m_cjson, m_rjson)
          scan_decoded_uuid(ir, v.type_, cfg, m_uuid)
        }
      }
      @ir.Alias(a) =>
        scan_ft_usage(a.target, cfg, m_uuid, m_time, m_dummy, m_cjson, m_rjson)
    }
  }

  let c_uuid : Ref[Bool] = { val: false, }
  let c_time : Ref[Bool] = { val: false, }
  let c_model : Ref[Bool] = { val: false, }
  let c_cjson_dummy : Ref[Bool] = { val: false, }
  let c_rjson_dummy : Ref[Bool] = { val: false, }
  let mut c_ws = false
  let mut c_stream = false
  let mut c_path_params = false
  let mut c_send_request = false
  let mut c_api_error = false
  let mut c_decode_json = false
  for op in operations {
    let op_is_ws = is_ws_operation(op)
    let op_is_stream = is_streaming_operation(op)
    if op_is_ws {
      c_ws = true
    }
    if op_is_stream {
      c_stream = true
    }
    if !op_is_ws && !op_is_stream {
      c_send_request = true
    }
    for p in op.params {
      if p.location is @spec.Path {
        c_path_params = true
      }
      scan_ft_usage(
        p.type_,
        cfg,
        c_uuid,
        c_time,
        c_model,
        c_cjson_dummy,
        c_rjson_dummy,
      )
    }
    match op.body {
      @ir.Json(ft, ..) =>
        scan_ft_usage(
          ft, cfg, c_uuid, c_time, c_model, c_cjson_dummy, c_rjson_dummy,
        )
      @ir.Multipart(parts, ..) | @ir.FormUrlEncoded(parts, ..) =>
        for part in parts {
          if !part.is_binary {
            scan_ft_usage(
              part.type_,
              cfg,
              c_uuid,
              c_time,
              c_model,
              c_cjson_dummy,
              c_rjson_dummy,
            )
          }
        }
      @ir.Text(..) | @ir.Binary(..) | @ir.NoBody => ()
    }
    if !op_is_ws {
      let has_explicit_success = op.responses
        .iter()
        .any(r => is_success_status(r.status))
      for resp in op.responses {
        let include_as_success = is_success_status(resp.status) ||
          (!has_explicit_success && resp.status is @spec.Default)
        let include_as_typed_error = cfg.emit_typed_errors &&
          !include_as_success
        if include_as_success && !op_is_stream {
          c_api_error = true
        }
        if include_as_success && response_decodes_json_helper(ir, cfg, resp) {
          c_decode_json = true
        }
        if !include_as_success && !include_as_typed_error {
          continue
        }
        match resp.body_kind {
          @ir.Json(ft) => {
            scan_ft_usage(
              ft, cfg, c_uuid, c_time, c_model, c_cjson_dummy, c_rjson_dummy,
            )
            scan_decoded_uuid(ir, ft, cfg, c_uuid)
          }
          @ir.Other(Some(ft)) =>
            if include_as_success {
              scan_ft_usage(
                ft, cfg, c_uuid, c_time, c_model, c_cjson_dummy, c_rjson_dummy,
              )
              scan_decoded_uuid(ir, ft, cfg, c_uuid)
            }
          @ir.Stream(@ir.Ndjson(ft)) =>
            if include_as_success {
              scan_ft_usage(
                ft, cfg, c_uuid, c_time, c_model, c_cjson_dummy, c_rjson_dummy,
              )
              scan_decoded_uuid(ir, ft, cfg, c_uuid)
            }
          _ => ()
        }
        if include_as_success {
          for h in resp.headers {
            scan_ft_usage(
              h.type_,
              cfg,
              c_uuid,
              c_time,
              c_model,
              c_cjson_dummy,
              c_rjson_dummy,
            )
            scan_decoded_uuid(ir, h.type_, cfg, c_uuid)
          }
        }
      }
    }
  }

  {
    ir,
    cfg,
    spec_hash,
    operations,
    groups,
    resolved_type_names,
    resolved_op_names,
    validation_errors,
    spec_declares_security,
    can_eq,
    can_compare,
    model_uses_uuid: m_uuid.val,
    model_uses_time: m_time.val,
    model_uses_rjson: m_has_non_alias || m_rjson.val,
    model_uses_cjson: m_has_non_alias || m_cjson.val,
    client_uses_model: c_model.val,
    client_uses_uuid: c_uuid.val,
    client_uses_time: c_time.val,
    client_uses_ws: c_ws,
    client_uses_stream: c_stream,
    client_uses_path_params: c_path_params,
    client_uses_send_request: c_send_request,
    client_uses_api_error: c_api_error,
    client_uses_decode_json: c_decode_json,
  }
}

///|
fn GenContext::derives_for(
  self : GenContext,
  ir_name : String,
) -> Array[String] {
  let out : Array[String] = ["Debug"]
  if self.can_eq.get(ir_name).unwrap_or(false) {
    out.push("Eq")
  }
  if self.can_compare.get(ir_name).unwrap_or(false) {
    out.push("Compare")
  }
  out
}