// IR type model: field types, 4-state presence, named definitions, top-level
// document metadata, and immutable IrModel result.

///|
/// Primitive leaf types, carrying the OAS format that produced them
/// (empty string = no format).
#derive(Debug, Eq)
pub(all) enum Prim {
  Str(String)
  Int(String)
  Num(String)
  Bool
}

///|
/// A type expression in the IR. `FieldIR.type_` and `ParamIR.type_` store the
/// unwrapped base type while `Presence` records optionality/nullability;
/// `Optional(...)` is used in standalone type positions such as `AliasDef` or
/// `List(Optional(T))`.
#derive(Debug, Eq)
pub(all) enum FieldType {
  Prim(Prim)
  Named(String)
  List(FieldType)
  MapTo(FieldType)
  /// `T?` — from `nullable: true` or a `[X, null]` union in value/alias positions.
  Optional(FieldType)
  /// Free-form / undecodable-in-this-profile value; kept as raw JSON.
  JsonValue
}

///|
/// Four-state field/parameter presence:
/// - `Required`: must be present and non-null (`T`)
/// - `RequiredNullable`: must be present, may be JSON `null` (`T?` by default)
/// - `Optional`: may be absent, non-null when present (`T?`)
/// - `OptionalNullable`: may be absent or JSON `null` (`T?` by default;
///   tri-state in tri-state mode)
#derive(Debug, Eq)
pub(all) enum Presence {
  Required
  RequiredNullable
  Optional
  OptionalNullable
}

///|
/// True when the field maps to `T?` in default (non-tri-state) codegen.
pub fn Presence::is_optional(self : Presence) -> Bool {
  !(self is Required)
}

///|
/// True when the property/parameter MUST be present on the wire
/// (`Required` or `RequiredNullable`).
pub fn Presence::is_required(self : Presence) -> Bool {
  self is (Required | RequiredNullable)
}

///|
/// True when JSON `null` is valid for this field.
pub fn Presence::allows_null(self : Presence) -> Bool {
  self is (RequiredNullable | OptionalNullable)
}

///|
#derive(Debug, Eq)
pub(all) struct FieldIR {
  /// MoonBit-safe identifier (uniquified per record by the builder).
  name : String
  /// The wire/property name as written in the spec.
  wire : String
  /// Unwrapped base type (nullability/optionality lives on `presence`).
  type_ : FieldType
  presence : Presence
  default : @spec.Node?
  example : @spec.Node?
  deprecated : Bool
  read_only : Bool
  write_only : Bool
  constraints : @spec.SchemaConstraints
  docs : Array[String]
}

///|
/// A tagged-union variant payload.
/// - `Unit`: tag property alone (`{"type": "Get"}`)
/// - `NewType(T)`: internally flattened payload (`{"type": "Key", ...T}`)
/// - `Fields(fs)`: inline sibling fields in the same object (`{"tag": "other", "value": ...}`)
#derive(Debug, Eq)
pub(all) enum VariantPayload {
  Unit
  NewType(FieldType)
  Fields(Array[FieldIR])
}

///|
#derive(Debug, Eq)
pub(all) struct VariantIR {
  /// MoonBit-safe Pascal variant name (uniquified within the enum).
  name : String
  /// The wire tag value (`{"type": "Key"}` -> `"Key"`).
  wire_tag : String
  payload : VariantPayload
  docs : Array[String]
}

///|
/// One variant of a string enum (pre-computed MoonBit name + wire value).
#derive(Debug, Eq)
pub(all) struct StringEnumVariant {
  name : String
  wire : String
}

///|
/// One branch of a shape-distinguishable untagged structural union
/// (e.g. `number | {$float: ...}`).
#derive(Debug, Eq)
pub(all) struct UntaggedVariantIR {
  name : String
  type_ : FieldType
}

///|
/// Record definition payload.
#derive(Debug, Eq)
pub(all) struct RecordDef {
  name : String
  fields : Array[FieldIR]
  docs : Array[String]
  example : @spec.Node?
  deprecated : Bool
  /// Source component name (or promotion context, for diagnostics).
  source : String
}

///|
/// Tagged-union definition payload.
#derive(Debug, Eq)
pub(all) struct TaggedEnumDef {
  name : String
  /// Wire property carrying the tag (`type`, `kind`, `tag`, `rule`, ...).
  tag_property : String
  variants : Array[VariantIR]
  /// Open unions gain a fallback variant at codegen.
  open : Bool
  /// Pre-allocated MoonBit name for the open fallback variant (when `open`),
  /// guaranteed not to collide with any known variant name.
  unknown_variant : String?
  docs : Array[String]
  example : @spec.Node?
  deprecated : Bool
  source : String
}

///|
/// String-enum definition payload.
#derive(Debug, Eq)
pub(all) struct StringEnumDef {
  name : String
  /// Variants in spec order (MoonBit PascalCase name + raw wire value).
  variants : Array[StringEnumVariant]
  /// Open enums gain a fallback variant (`Unknown(String)` or collision-free
  /// name stored in `unknown_variant`) at codegen.
  open : Bool
  /// Pre-allocated MoonBit name for the open fallback variant (when `open`),
  /// guaranteed not to collide with any variant such as `"unknown" -> Unknown`.
  unknown_variant : String?
  docs : Array[String]
  example : @spec.Node?
  deprecated : Bool
  source : String
}

///|
/// Shape-distinguishable untagged union (e.g. `number | object`).
#derive(Debug, Eq)
pub(all) struct UntaggedEnumDef {
  name : String
  variants : Array[UntaggedVariantIR]
  docs : Array[String]
  example : @spec.Node?
  deprecated : Bool
  source : String
}

///|
/// Alias definition payload.
#derive(Debug, Eq)
pub(all) struct AliasDef {
  name : String
  target : FieldType
  docs : Array[String]
  example : @spec.Node?
  deprecated : Bool
  source : String
}

///|
/// A named definition in the registry.
#derive(Debug, Eq)
pub(all) enum TypeDef {
  Record(RecordDef)
  TaggedEnum(TaggedEnumDef)
  StringEnum(StringEnumDef)
  UntaggedEnum(UntaggedEnumDef)
  Alias(AliasDef)
}

///|
/// The MoonBit-safe name of a definition.
pub fn TypeDef::name(self : TypeDef) -> String {
  match self {
    Record(data) => data.name
    TaggedEnum(data) => data.name
    StringEnum(data) => data.name
    UntaggedEnum(data) => data.name
    Alias(data) => data.name
  }
}

///|
/// The source component/context name of a definition.
pub fn TypeDef::source(self : TypeDef) -> String {
  match self {
    Record(data) => data.source
    TaggedEnum(data) => data.source
    StringEnum(data) => data.source
    UntaggedEnum(data) => data.source
    Alias(data) => data.source
  }
}

///|
/// Lowered top-level OpenAPI document metadata exposed on `IrModel`.
#derive(Debug, Eq)
pub(all) struct InfoIR {
  title : String
  version : String
  description : String?
}

///|
/// A single variable placeholder declared inside an OpenAPI server URL template.
#derive(Debug, Eq)
pub(all) struct ServerVariableIR {
  name : String
  default : String
  enum_ : Array[String]
  description : String?
}

///|
/// A lowered OpenAPI server entry with its URL template and variables.
#derive(Debug, Eq)
pub(all) struct ServerIR {
  url : String
  description : String?
  variables : Array[ServerVariableIR]
}

///|
/// Expand `{var}` templates in a single pass using each variable's `default`
/// value (OAS §4.7.5 literal substitution, immune to chained placeholder
/// expansion when a variable's value itself contains `{other}`).
pub fn ServerIR::default_url(self : ServerIR) -> String {
  if self.variables.is_empty() {
    return self.url
  }
  let vals : Map[String, String] = Map([])
  for v in self.variables {
    vals[v.name] = v.default
  }
  let out = StringBuilder()
  let mut i : Int32 = 0
  let n = self.url.length()
  while i < n {
    if self.url[i] == '{' {
      let mut j = i + 1
      while j < n && self.url[j] != '}' && self.url[j] != '{' {
        j += 1
      }
      if j < n && self.url[j] == '}' {
        let key = self.url[i + 1:j].to_owned()
        match vals.get(key) {
          Some(v) => {
            out.write_string(v)
            i = j + 1
            continue
          }
          None => ()
        }
      }
    }
    let next = i + 1
    out.write_string(self.url[i:next].to_owned())
    i = next
  }
  out.to_string()
}

///|
/// A lowered top-level OpenAPI tag declaration.
#derive(Debug, Eq)
pub(all) struct TagIR {
  name : String
  description : String?
}

///|
/// A lowered OpenAPI `components.securitySchemes` entry.
#derive(Debug, Eq)
pub(all) struct SecuritySchemeIR {
  name : String
  type_ : @spec.SecuritySchemeType
  description : String?
}

///|
/// IR lowering options controlling open-enum/union fallbacks and tag grouping.
#derive(Debug, Eq)
pub(all) struct IrOptions {
  open_string_enums : Bool
  open_tagged_unions : Bool
  /// Generic/umbrella tags de-prioritized during tag grouping.
  global_tags : Array[String]
}

///|
/// Default options: closed enums, no hardcoded global tags.
pub fn IrOptions::default() -> IrOptions {
  { open_string_enums: false, open_tagged_unions: false, global_tags: [], }
}

///|
/// The immutable semantic IR produced by `build_ir`: ordered type registry,
/// operations, tag groups, component accounting, document metadata, and
/// diagnostics.
pub struct IrModel {
  priv defs : Array[TypeDef]
  priv types : Map[String, TypeDef]
  priv component_names : Map[String, String]
  priv accounting : Array[(String, String)]
  priv operations : Array[OpIR]
  priv groups : Array[(String, Array[String])]
  priv diags : @spec.Diagnostics
  priv info : InfoIR
  priv servers : Array[ServerIR]
  priv tags : Array[TagIR]
  priv security_schemes : Array[SecuritySchemeIR]
}

///|
/// Diagnostics accumulated during spec loading and IR lowering.
pub fn IrModel::diags(self : IrModel) -> @spec.Diagnostics {
  self.diags
}

///|
/// All lowered type definitions in deterministic emission order.
pub fn IrModel::defs(self : IrModel) -> Array[TypeDef] {
  self.defs.copy()
}

///|
/// Accounting log mapping source component names to lowered MoonBit names or dispositions.
pub fn IrModel::accounting(self : IrModel) -> Array[(String, String)] {
  self.accounting.copy()
}

///|
/// All lowered HTTP and WebSocket operations.
pub fn IrModel::operations(self : IrModel) -> Array[OpIR] {
  self.operations.copy()
}

///|
/// Operation groups as `(group_name, operation_ids)` pairs.
pub fn IrModel::groups(self : IrModel) -> Array[(String, Array[String])] {
  self.groups.copy()
}

///|
/// Document title, version, and optional description.
pub fn IrModel::info(self : IrModel) -> InfoIR {
  self.info
}

///|
/// Top-level OpenAPI `servers` entries.
pub fn IrModel::servers(self : IrModel) -> Array[ServerIR] {
  self.servers.copy()
}

///|
/// Top-level OpenAPI `tags` entries.
pub fn IrModel::tags(self : IrModel) -> Array[TagIR] {
  self.tags.copy()
}

///|
/// Top-level OpenAPI `components.securitySchemes` entries.
pub fn IrModel::security_schemes(self : IrModel) -> Array[SecuritySchemeIR] {
  self.security_schemes.copy()
}

///|
/// Look up a definition by MoonBit name.
pub fn IrModel::def(self : IrModel, name : String) -> TypeDef? {
  self.types.get(name)
}

///|
/// The MoonBit name a component maps to, if defined/folded.
pub fn IrModel::component_name(self : IrModel, component : String) -> String? {
  self.component_names.get(component)
}