///|
priv struct CompiledObjectField {
  name : String
  schema : CompiledNode
  required : Bool
}

///|
priv struct CompiledRefSlot {
  mut target : CompiledNode?
}

///|
priv enum CompiledNode {
  Any
  Empty
  Null
  Boolean
  Integer(min~ : Int64?, max~ : Int64?)
  Int64String(min~ : Int64?, max~ : Int64?, is_uint64~ : Bool)
  Number(min~ : Double?, max~ : Double?)
  String(
    min_len~ : Int32?,
    max_len~ : Int32?,
    format~ : String?,
    pattern~ : String?,
  )
  Array(items~ : CompiledNode, min_items~ : Int32?, max_items~ : Int32?)
  Record(value~ : CompiledNode)
  Object(
    fields~ : Array[CompiledObjectField],
    field_index~ : Map[String, CompiledObjectField],
    additional_properties~ : Bool,
  )
  Enum(value_set~ : Map[String, Bool], expected_desc~ : String)
  Union(variants~ : Array[CompiledNode])
  Nullable(CompiledNode)
  RefSlot(CompiledRefSlot)
}

///|
/// Precompiled, cycle-safe JSON Schema validator & normalizer.
/// Resolves `SchemaRef` once and pre-builds immutable `Object` field lookup maps
/// so validating large arrays or hot route payloads allocates zero intermediate maps.
pub struct CompiledSchema {
  priv source : SchemaNode
  priv root : CompiledNode
}

///|
fn compile_node(
  node : SchemaNode,
  refs : Map[String, CompiledRefSlot],
) -> CompiledNode {
  match node {
    Any => CompiledNode::Any
    Empty => CompiledNode::Empty
    Null => CompiledNode::Null
    Boolean(..) => CompiledNode::Boolean
    Integer(min~, max~, ..) => CompiledNode::Integer(min~, max~)
    Int64String(min~, max~, meta~) =>
      CompiledNode::Int64String(
        min~,
        max~,
        is_uint64=meta.format == Some("uint64"),
      )
    Number(min~, max~, ..) => CompiledNode::Number(min~, max~)
    String(min_len~, max_len~, meta~) =>
      CompiledNode::String(
        min_len~,
        max_len~,
        format=meta.format,
        pattern=meta.pattern,
      )
    Array(items~, min_items~, max_items~, ..) =>
      CompiledNode::Array(
        items=compile_node(items, refs),
        min_items~,
        max_items~,
      )
    Record(value~, ..) => CompiledNode::Record(value=compile_node(value, refs))
    Object(fields~, additional_properties~, ..) => {
      let compiled_fields : Array[CompiledObjectField] = Array(
        capacity=fields.length(),
      )
      let field_index : Map[String, CompiledObjectField] = Map([])
      for f in fields {
        let cf : CompiledObjectField = {
          name: f.name,
          schema: compile_node(f.schema, refs),
          required: f.required,
        }
        compiled_fields.push(cf)
        field_index[f.name] = cf
      }
      CompiledNode::Object(
        fields=compiled_fields,
        field_index~,
        additional_properties~,
      )
    }
    Enum(values~, ..) => {
      let value_set : Map[String, Bool] = Map([])
      for v in values {
        value_set[v] = true
      }
      CompiledNode::Enum(value_set~, expected_desc=values.join(" | "))
    }
    Union(variants~, ..) => {
      let compiled_variants : Array[CompiledNode] = Array(
        capacity=variants.length(),
      )
      for v in variants {
        compiled_variants.push(compile_node(v, refs))
      }
      CompiledNode::Union(variants=compiled_variants)
    }
    Nullable(inner) => CompiledNode::Nullable(compile_node(inner, refs))
    Ref(r) =>
      match refs.get(r.id) {
        Some(slot) => CompiledNode::RefSlot(slot)
        None => {
          let slot : CompiledRefSlot = { target: None, }
          refs[r.id] = slot
          let compiled = compile_node(r.resolve(), refs)
          slot.target = Some(compiled)
          CompiledNode::RefSlot(slot)
        }
      }
  }
}

///|
/// Compiles a `SchemaNode` into a reusable, pre-indexed `CompiledSchema`.
pub fn CompiledSchema::compile(schema : SchemaNode) -> CompiledSchema {
  let refs : Map[String, CompiledRefSlot] = Map([])
  let root = compile_node(schema, refs)
  { source: schema, root, }
}

///|
/// Returns the original `SchemaNode` from which this `CompiledSchema` was compiled.
pub fn CompiledSchema::schema(self : CompiledSchema) -> SchemaNode {
  self.source
}

///|
fn validate_compiled_rec(
  value : Json,
  node : CompiledNode,
  path : String,
  issues : Array[ValidationIssue],
) -> Unit {
  match node {
    Any => ()
    Empty =>
      match value {
        Null => ()
        _ =>
          issues.push({
            path,
            message: "expected empty/null payload",
            expected: "empty",
          })
      }
    Null =>
      match value {
        Null => ()
        _ => issues.push({ path, message: "expected null", expected: "null", })
      }
    Boolean =>
      match value {
        True | False => ()
        _ =>
          issues.push({
            path,
            message: "expected boolean",
            expected: "boolean",
          })
      }
    Integer(min~, max~) =>
      match value {
        Number(n, ..) =>
          match as_exact_safe_int64(n) {
            None =>
              if n.is_nan() || n.is_inf() {
                issues.push({
                  path,
                  message: "expected finite integer",
                  expected: "integer",
                })
              } else if n >= 9223372036854775808.0 ||
                n < -9223372036854775808.0 ||
                n.abs() > 9007199254740991.0 {
                issues.push({
                  path,
                  message: "integer out of IEEE-754 safe range; use Int64String",
                  expected: "safe integer",
                })
              } else {
                issues.push({
                  path,
                  message: "expected integer, got fractional number",
                  expected: "integer",
                })
              }
            Some(truncated) => {
              match min {
                Some(lo) =>
                  if truncated < lo {
                    issues.push({
                      path,
                      message: "integer must be >= \{lo}",
                      expected: "integer >= \{lo}",
                    })
                  }
                None => ()
              }
              match max {
                Some(hi) =>
                  if truncated > hi {
                    issues.push({
                      path,
                      message: "integer must be <= \{hi}",
                      expected: "integer <= \{hi}",
                    })
                  }
                None => ()
              }
            }
          }
        _ =>
          issues.push({
            path,
            message: "expected integer",
            expected: "integer",
          })
      }
    Int64String(min~, max~, is_uint64~) =>
      match value {
        String(s) =>
          if !is_signed_int_str(s) {
            issues.push({
              path,
              message: "expected base-10 integer string",
              expected: "int64 string",
            })
          } else if is_uint64 {
            match (Some(@string.parse_uint64(s)) catch { _ => None }) {
              Some(u) => {
                match min {
                  Some(lo) =>
                    if lo > 0L && u < lo.reinterpret_as_uint64() {
                      issues.push({
                        path,
                        message: "uint64 must be >= \{lo}",
                        expected: "uint64 >= \{lo}",
                      })
                    }
                  None => ()
                }
                match max {
                  Some(hi) =>
                    if hi < 0L || u > hi.reinterpret_as_uint64() {
                      issues.push({
                        path,
                        message: "uint64 must be <= \{hi}",
                        expected: "uint64 <= \{hi}",
                      })
                    }
                  None => ()
                }
              }
              None =>
                issues.push({
                  path,
                  message: "invalid unsigned 64-bit integer string",
                  expected: "uint64 string",
                })
            }
          } else {
            match (Some(@string.parse_int64(s)) catch { _ => None }) {
              None =>
                issues.push({
                  path,
                  message: "int64 string out of range",
                  expected: "int64 string",
                })
              Some(v) => {
                match min {
                  Some(lo) =>
                    if v < lo {
                      issues.push({
                        path,
                        message: "int64 must be >= \{lo}",
                        expected: "int64 >= \{lo}",
                      })
                    }
                  None => ()
                }
                match max {
                  Some(hi) =>
                    if v > hi {
                      issues.push({
                        path,
                        message: "int64 must be <= \{hi}",
                        expected: "int64 <= \{hi}",
                      })
                    }
                  None => ()
                }
              }
            }
          }
        _ =>
          issues.push({
            path,
            message: "expected int64 encoded as JSON string",
            expected: "int64 string",
          })
      }
    Number(min~, max~) =>
      match value {
        Number(n, ..) =>
          if n.is_nan() || n.is_inf() {
            issues.push({
              path,
              message: "expected finite number",
              expected: "finite number",
            })
          } else {
            match min {
              Some(lo) =>
                if n < lo {
                  issues.push({
                    path,
                    message: "number must be >= \{lo}",
                    expected: "number >= \{lo}",
                  })
                }
              None => ()
            }
            match max {
              Some(hi) =>
                if n > hi {
                  issues.push({
                    path,
                    message: "number must be <= \{hi}",
                    expected: "number <= \{hi}",
                  })
                }
              None => ()
            }
          }
        _ =>
          issues.push({ path, message: "expected number", expected: "number", })
      }
    String(min_len~, max_len~, format~, pattern~) =>
      match value {
        String(s) => {
          if min_len is Some(_) || max_len is Some(_) {
            let char_len = s.char_length()
            match min_len {
              Some(lo) =>
                if char_len < lo {
                  issues.push({
                    path,
                    message: "string length must be >= \{lo}",
                    expected: "string(min_len=\{lo})",
                  })
                }
              None => ()
            }
            match max_len {
              Some(hi) =>
                if char_len > hi {
                  issues.push({
                    path,
                    message: "string length must be <= \{hi}",
                    expected: "string(max_len=\{hi})",
                  })
                }
              None => ()
            }
          }
          match format {
            Some(fmt) => validate_string_format(s, fmt, path, issues)
            None => ()
          }
          match pattern {
            Some(pat) =>
              if !matches_pattern(s, pat) {
                issues.push({
                  path,
                  message: "string does not match pattern '\{pat}'",
                  expected: "pattern(\{pat})",
                })
              }
            None => ()
          }
        }
        _ =>
          issues.push({ path, message: "expected string", expected: "string", })
      }
    Array(items~, min_items~, max_items~) =>
      match value {
        Array(arr) => {
          match min_items {
            Some(lo) =>
              if arr.length() < lo {
                issues.push({
                  path,
                  message: "array length must be >= \{lo}",
                  expected: "array(min_items=\{lo})",
                })
              }
            None => ()
          }
          match max_items {
            Some(hi) =>
              if arr.length() > hi {
                issues.push({
                  path,
                  message: "array length must be <= \{hi}",
                  expected: "array(max_items=\{hi})",
                })
              }
            None => ()
          }
          for i in 0..
          issues.push({ path, message: "expected array", expected: "array", })
      }
    Record(value=val_schema) =>
      match value {
        Object(map) =>
          map.each((k, v) => {
            validate_compiled_rec(
              v,
              val_schema,
              append_pointer(path, k),
              issues,
            )
          })
        _ =>
          issues.push({ path, message: "expected object", expected: "record", })
      }
    Object(fields~, field_index~, additional_properties~) =>
      match value {
        Object(map) => {
          for f in fields {
            match map.get(f.name) {
              Some(v) =>
                validate_compiled_rec(
                  v,
                  f.schema,
                  append_pointer(path, f.name),
                  issues,
                )
              None =>
                if f.required {
                  issues.push({
                    path: append_pointer(path, f.name),
                    message: "missing required field '\{f.name}'",
                    expected: "required",
                  })
                }
            }
          }
          if !additional_properties {
            map.each((k, _v) => {
              if !field_index.contains(k) {
                issues.push({
                  path: append_pointer(path, k),
                  message: "unexpected additional property '\{k}'",
                  expected: "no additional properties",
                })
              }
            })
          }
        }
        _ =>
          issues.push({ path, message: "expected object", expected: "object", })
      }
    Enum(value_set~, expected_desc~) =>
      match value {
        String(s) =>
          if !value_set.contains(s) {
            issues.push({
              path,
              message: "value '\{s}' is not in enum",
              expected: expected_desc,
            })
          }
        _ =>
          issues.push({
            path,
            message: "expected enum string",
            expected: expected_desc,
          })
      }
    Union(variants~) => {
      let mut matched = false
      for variant in variants {
        let trial : Array[ValidationIssue] = []
        validate_compiled_rec(value, variant, path, trial)
        if trial.is_empty() {
          matched = true
          break
        }
      }
      if !matched {
        issues.push({
          path,
          message: "value does not match any union variant",
          expected: "union",
        })
      }
    }
    Nullable(inner) =>
      match value {
        Null => ()
        other => validate_compiled_rec(other, inner, path, issues)
      }
    RefSlot(slot) =>
      match slot.target {
        Some(target) => validate_compiled_rec(value, target, path, issues)
        None => ()
      }
  }
}

///|
/// Validates a `Json` value against this precompiled schema.
pub fn CompiledSchema::validate(
  self : CompiledSchema,
  value : Json,
) -> Array[ValidationIssue] {
  let issues : Array[ValidationIssue] = []
  validate_compiled_rec(value, self.root, "", issues)
  issues
}

///|
fn normalize_compiled_rec(value : Json, node : CompiledNode) -> Json {
  match node {
    RefSlot(slot) =>
      match slot.target {
        Some(target) => normalize_compiled_rec(value, target)
        None => value
      }
    Nullable(inner) =>
      match value {
        Null => Json::null()
        other => normalize_compiled_rec(other, inner)
      }
    Object(fields~, field_index~, additional_properties~) =>
      match value {
        Object(map) => {
          let out : Map[String, Json] = Map([])
          for f in fields {
            match map.get(f.name) {
              Some(v) => out[f.name] = normalize_compiled_rec(v, f.schema)
              None => ()
            }
          }
          if additional_properties {
            map.each((k, v) => if !field_index.contains(k) { out[k] = v })
          }
          Json::object(out)
        }
        other => other
      }
    Array(items~, ..) =>
      match value {
        Array(arr) =>
          Json::array(arr.map(el => normalize_compiled_rec(el, items)))
        other => other
      }
    Record(value=val_schema) =>
      match value {
        Object(map) => {
          let out : Map[String, Json] = Map([])
          map.each((k, v) => out[k] = normalize_compiled_rec(v, val_schema))
          Json::object(out)
        }
        other => other
      }
    Union(variants~) => {
      for variant in variants {
        let trial : Array[ValidationIssue] = []
        validate_compiled_rec(value, variant, "", trial)
        if trial.is_empty() {
          return normalize_compiled_rec(value, variant)
        }
      }
      value
    }
    _ => value
  }
}

///|
/// Strips undeclared fields from `value` using this precompiled schema without allocating per-object lookup maps.
pub fn CompiledSchema::normalize(self : CompiledSchema, value : Json) -> Json {
  normalize_compiled_rec(value, self.root)
}