///|
/// A violated assertion in the target schema, located by JSON Pointer.
pub(all) struct RejectionDiagnostic {
  instance_path : String
  keyword : String
  missing_property : String?
}

///|
priv struct DiagnosticSearch {
  mut remaining : Int32
}

///|
priv enum DiagnosticSegment {
  Member(String)
  Index(Int32)
}

///|
priv struct ViolatedAssertion {
  keyword : String
  missing_property : String?
}

///|
fn violated(keyword : String) -> ViolatedAssertion? {
  Some({ keyword, missing_property: None, })
}

///|
fn DiagnosticSearch::spend(
  self : DiagnosticSearch,
  units~ : Int32 = 1,
) -> Unit raise SchemaIssue {
  if units > self.remaining {
    raise Unsupported("rejection diagnostic work limit exceeded")
  }
  self.remaining -= units
}

///|
fn DiagnosticSearch::pointer(
  self : DiagnosticSearch,
  path : Array[DiagnosticSegment],
  output_budget : Ref[Int32],
) -> String raise SchemaIssue {
  let pointer = StringBuilder()
  for segment in path.rev_iter() {
    spend_output_budget(output_budget, 1)
    pointer.write_char('/')
    match segment {
      Index(index) => {
        let token = index.to_string()
        spend_output_budget(output_budget, token.length())
        pointer.write_string(token)
      }
      Member(name) => {
        self.spend(units=name.length())
        spend_output_budget(output_budget, name.length())
        for char in name.iter() {
          match char {
            '~' => {
              spend_output_budget(output_budget, 1)
              pointer.write_string("~0")
            }
            '/' => {
              spend_output_budget(output_budget, 1)
              pointer.write_string("~1")
            }
            _ => pointer.write_char(char)
          }
        }
      }
    }
  }
  pointer.to_string()
}

///|
fn DiagnosticSearch::exact_number(
  self : DiagnosticSearch,
  number : Double,
  repr : String?,
) -> Double raise SchemaIssue {
  if !number.is_finite() {
    raise Unsupported("rejection diagnostic requires a finite witness number")
  }
  // A fractional double cannot be the rounding of an integer. Every schema
  // bound is an exactly represented integer, so fractional comparisons are safe.
  if number.trunc() != number {
    return number
  }
  // The solver generates doubles with exact integral values, including the two
  // representatives immediately outside the supported integer literal range.
  let limit = integer_literal_limit + 1L
  let exact = match repr {
    None if number.abs() <= limit.to_double() => number.to_int64()
    Some(raw) => {
      self.spend(units=raw.length())
      @string.parse_int64(raw) catch {
        _ =>
          raise Unsupported(
            "rejection diagnostic cannot confirm integer rounding",
          )
      }
    }
    None =>
      raise Unsupported(
        "rejection diagnostic witness number exceeds the exact range",
      )
  }
  if exact < -limit || exact > limit {
    raise Unsupported(
      "rejection diagnostic witness number exceeds the exact range",
    )
  }
  exact.to_double()
}

///|
fn DiagnosticSearch::matches_kind(
  self : DiagnosticSearch,
  kind : String,
  instance : Json,
) -> Bool raise SchemaIssue {
  match (kind, instance) {
    ("integer", Number(number, repr~)) => {
      let number = self.exact_number(number, repr)
      number.trunc() == number
    }
    ("number", Number(number, repr~)) if number.is_finite() || repr is Some(_) =>
      true
    ("string", String(_))
    | ("boolean", True | False)
    | ("null", Null)
    | ("object", Object(_))
    | ("array", Array(_)) => true
    (
      "integer"
      | "number"
      | "string"
      | "boolean"
      | "null"
      | "object"
      | "array",
      _,
    ) => false
    _ => raise Unsupported("unsupported type in rejection diagnostic")
  }
}

///|
fn DiagnosticSearch::matches_type(
  self : DiagnosticSearch,
  constraint : Json,
  instance : Json,
) -> Bool raise SchemaIssue {
  match constraint {
    String(kind) => self.matches_kind(kind, instance)
    Array(kinds) if !kinds.is_empty() => {
      for kind in kinds {
        self.spend()
        guard kind is String(name) else {
          raise Unsupported("type requires a string type name")
        }
        if self.matches_kind(name, instance) {
          return true
        }
      }
      false
    }
    _ => raise Unsupported("type requires a string or a nonempty array")
  }
}

///|
fn DiagnosticSearch::matches_literal(
  self : DiagnosticSearch,
  literal : Json,
  instance : Json,
  keyword : String,
) -> Bool raise SchemaIssue {
  match (literal, instance) {
    (Number(_, repr=_), Number(number, repr~)) =>
      integer_literal(literal, keyword).to_double() ==
      self.exact_number(number, repr)
    (String(expected), String(actual)) => {
      self.spend(units=expected.length().min(actual.length()) / 16)
      expected == actual
    }
    (Object(_), Object(_)) | (Array(_), Array(_)) =>
      raise Unsupported(
        "rejection diagnostic supports scalar literal comparison",
      )
    _ => literal == instance
  }
}

///|
fn DiagnosticSearch::matches_enum(
  self : DiagnosticSearch,
  constraint : Json,
  instance : Json,
) -> Bool raise SchemaIssue {
  for literal in nonempty_array(constraint, "enum") {
    self.spend()
    if self.matches_literal(literal, instance, "enum") {
      return true
    }
  }
  false
}

///|
fn violates_length(
  keyword : String,
  constraint : Json,
  length : Int32,
) -> Bool raise SchemaIssue {
  let limit = nonnegative_length(constraint, keyword)
  if keyword.has_prefix("min") {
    length.to_int64() < limit
  } else {
    length.to_int64() > limit
  }
}

///|
fn DiagnosticSearch::check_members(
  self : DiagnosticSearch,
  members : Map[String, Json],
  fields : Map[String, Json],
  path : Array[DiagnosticSegment]?,
  depth : Int32,
) -> ViolatedAssertion? raise SchemaIssue {
  let properties = match fields.get("properties") {
    None => None
    Some(Object(properties)) => Some(properties)
    Some(_) => raise Unsupported("properties requires an object")
  }
  let additional = fields
    .get("additionalProperties")
    .unwrap_or(Json::boolean(true))
  if properties is None && additional is True {
    return None
  }
  for name, instance in members {
    self.spend(units=1 + name.length() / 16)
    let property = match properties {
      Some(properties) => properties.get(name)
      None => None
    }
    let schema = match property {
      Some(schema) => schema
      None if additional is False => return violated("additionalProperties")
      None => additional
    }
    if self.check(schema, instance, path, depth + 1) is Some(failure) {
      if path is Some(path) {
        path.push(Member(name))
      }
      return Some(failure)
    }
  }
  None
}

///|
fn DiagnosticSearch::check_elements(
  self : DiagnosticSearch,
  elements : Array[Json],
  fields : Map[String, Json],
  path : Array[DiagnosticSegment]?,
  depth : Int32,
) -> ViolatedAssertion? raise SchemaIssue {
  let prefix = match fields.get("prefixItems") {
    None => []
    Some(prefix) => nonempty_array(prefix, "prefixItems")
  }
  let items = fields.get("items").unwrap_or(Json::boolean(true))
  for index, instance in elements {
    let schema = if index < prefix.length() {
      prefix[index]
    } else {
      match items {
        True => break
        False => return violated("items")
        _ => items
      }
    }
    if self.check(schema, instance, path, depth + 1) is Some(failure) {
      if path is Some(path) {
        path.push(Index(index))
      }
      return Some(failure)
    }
  }
  None
}

///|
fn DiagnosticSearch::check_alternatives(
  self : DiagnosticSearch,
  branches : Json,
  keyword : String,
  instance : Json,
  depth : Int32,
) -> ViolatedAssertion? raise SchemaIssue {
  let exclusive = keyword == "oneOf"
  let mut matched = false
  for branch in nonempty_array(branches, keyword) {
    // A failed branch only contributes to the aggregate result.
    if self.check(branch, instance, None, depth + 1) is None {
      if !exclusive {
        return None
      }
      if matched {
        return violated(keyword)
      }
      matched = true
    }
  }
  if matched {
    None
  } else {
    violated(keyword)
  }
}

///|
fn DiagnosticSearch::check_assertions(
  self : DiagnosticSearch,
  fields : Map[String, Json],
  instance : Json,
  path : Array[DiagnosticSegment]?,
  depth : Int32,
) -> ViolatedAssertion? raise SchemaIssue {
  for keyword, constraint in fields {
    self.spend()
    match keyword {
      "type"
      | "const"
      | "enum"
      | "minimum"
      | "maximum"
      | "exclusiveMinimum"
      | "exclusiveMaximum"
      | "minLength"
      | "maxLength"
      | "minProperties"
      | "maxProperties"
      | "required"
      | "properties"
      | "additionalProperties"
      | "minItems"
      | "maxItems"
      | "items"
      | "prefixItems"
      | "anyOf"
      | "oneOf"
      | "allOf" => ()
      _ => check_annotation(keyword, constraint)
    }
  }
  if fields.get("type") is Some(constraint) &&
    !self.matches_type(constraint, instance) {
    return violated("type")
  }
  let mut code_points = None
  for keyword, constraint in fields {
    match (keyword, instance) {
      ("enum", _) if !self.matches_enum(constraint, instance) =>
        return violated(keyword)
      ("const", _) if !self.matches_literal(constraint, instance, keyword) =>
        return violated(keyword)
      (
        "minimum"
        | "maximum"
        | "exclusiveMinimum"
        | "exclusiveMaximum",
        Number(number, repr~),
      ) => {
        let bound = integer_literal(constraint, keyword).to_double()
        let number = self.exact_number(number, repr)
        let failed = match keyword {
          "minimum" => number < bound
          "maximum" => number > bound
          "exclusiveMinimum" => number <= bound
          _ => number >= bound
        }
        if failed {
          return violated(keyword)
        }
      }
      ("minLength" | "maxLength", String(text)) => {
        let length = match code_points {
          Some(length) => length
          None => {
            self.spend(units=text.length())
            let length = text.iter().count()
            code_points = Some(length)
            length
          }
        }
        if violates_length(keyword, constraint, length) {
          return violated(keyword)
        }
      }
      ("minProperties" | "maxProperties", Object(members)) if violates_length(
          keyword,
          constraint,
          members.length(),
        ) => return violated(keyword)
      ("required", Object(members)) => {
        guard constraint is Array(names) else {
          raise Unsupported("required requires an array")
        }
        for name in names {
          guard name is String(name) else {
            raise Unsupported("required requires string property names")
          }
          self.spend(units=1 + name.length() / 16)
          if !members.contains(name) {
            return Some({ keyword, missing_property: Some(name), })
          }
        }
      }
      ("minItems" | "maxItems", Array(items)) if violates_length(
          keyword,
          constraint,
          items.length(),
        ) => return violated(keyword)
      ("anyOf" | "oneOf", _) =>
        if self.check_alternatives(constraint, keyword, instance, depth)
          is Some(failure) {
          return Some(failure)
        }
      ("allOf", _) =>
        for branch in nonempty_array(constraint, keyword) {
          if self.check(branch, instance, path, depth + 1) is Some(failure) {
            return Some(failure)
          }
        }
      _ => ()
    }
  }
  match instance {
    Object(members) => self.check_members(members, fields, path, depth)
    Array(items) => self.check_elements(items, fields, path, depth)
    _ => None
  }
}

///|
fn DiagnosticSearch::check(
  self : DiagnosticSearch,
  schema : Json,
  instance : Json,
  path : Array[DiagnosticSegment]?,
  depth : Int32,
) -> ViolatedAssertion? raise SchemaIssue {
  self.spend()
  if depth > 128 {
    raise Unsupported("rejection diagnostic exceeds the nesting depth limit")
  }
  match schema {
    True => None
    False => violated("false")
    Object(fields) => self.check_assertions(fields, instance, path, depth)
    _ => raise Unsupported("expected a schema object or boolean")
  }
}

///|
// Revalidate the rendered counterexample against the expanded target. A limit
// reached during explanation does not change the solver's verdict.
fn diagnose_rejection(target : Json, witness : Json) -> RejectionDiagnostic? {
  let search : DiagnosticSearch = { remaining: comparison_work_limit, }
  let path : Array[DiagnosticSegment] = []
  try {
    match search.check(target, witness, Some(path), 0) {
      None => None
      Some(failure) => {
        let output_budget = Ref(output_size_limit)
        if failure.missing_property is Some(name) {
          spend_output_budget(output_budget, name.length())
        }
        Some({
          instance_path: search.pointer(path, output_budget),
          keyword: failure.keyword,
          missing_property: failure.missing_property,
        })
      }
    }
  } catch {
    Unsupported(_) => None
  }
}