///|
/// Inclusion is directional: all values accepted by the source must be
/// accepted by the target.
pub(all) enum Verdict {
  Compatible
  Incompatible(Json)
  Unknown(String)
}

///|
pub fn Verdict::to_json(self : Verdict) -> Json {
  match self {
    Compatible => { "status": "compatible" }
    Incompatible(witness) => { "status": "incompatible", "witness": witness }
    Unknown(reason) => { "status": "unknown", "reason": Json::string(reason) }
  }
}

///|
/// A comparison and an optional location where the target rejects its witness.
pub(all) struct ComparisonReport {
  verdict : Verdict
  diagnostic : RejectionDiagnostic?
}

///|
pub fn ComparisonReport::to_json(self : ComparisonReport) -> Json {
  let result = self.verdict.to_json()
  if result is Object(fields) && self.diagnostic is Some(diagnostic) {
    let details : Map[String, Json] = {
      "instancePath": Json::string(diagnostic.instance_path),
      "keyword": Json::string(diagnostic.keyword),
    }
    if diagnostic.missing_property is Some(name) {
      details["missingProperty"] = Json::string(name)
    }
    fields["diagnostic"] = Json::object(details)
  }
  result
}

///|
priv suberror SchemaIssue {
  Unsupported(String)
}

///|
fn parse_document(text : String, label : String) -> Json raise SchemaIssue {
  @json.parse(text, reject_duplicate_keys=true, preserve_number_repr=true) catch {
    error => raise Unsupported("\{label}: invalid JSON: \{error}")
  }
}

///|
fn check_annotation(key : String, value : Json) -> Unit raise SchemaIssue {
  match (key, value) {
    // Both supported dialects use the format-annotation vocabulary.
    ("title" | "description" | "$comment" | "format", String(_)) => ()
    ("examples", Array(_)) => ()
    ("default", _) | ("deprecated" | "nullable", True | False) => ()
    ("$schema", String("https://json-schema.org/draft/2020-12/schema")) => ()
    ("$schema", String("https://spec.openapis.org/oas/3.1/dialect/base")) => ()
    _ => raise Unsupported("unsupported schema keyword or value: \{key}")
  }
}

///|
priv struct IntegerConstraints {
  lower : Int64?
  upper : Int64?
  values : Array[Interval]?
  work : Ref[Int32]
}

///|
priv struct CompiledSchema {
  non_null : NonNullDomain
  accepts_null : Bool
}

///|
priv enum NonNullDomain {
  AnyNonNull
  NoNonNull
  Scalar(Domain)
  Record(ObjectShape)
  Sequence(ArrayShape)
  Alternatives(Map[String, NonNullDomain])
}

///|
let all_values : CompiledSchema = { non_null: AnyNonNull, accepts_null: true, }

///|
let empty_value_set : CompiledSchema = {
  non_null: NoNonNull,
  accepts_null: false,
}

///|
priv enum Witness {
  Literal(Json)
  StringWitness(Int64, Char)
  ObjectWitness(ObjectShape, Int64, ObjectMember?)
  ArrayWitness(ArrayShape, Int64, (Int32, Witness)?)
}

///|
priv enum Domain {
  Integers(Array[Interval])
  Numbers
  Strings(StringDomain)
  Booleans(Array[Bool])
}

///|
priv enum StringDomain {
  StringLengths(StringLengthRange)
  StringValues(Array[String])
}

///|
let integer_literal_limit : Int64 = 9007199254740991L

///|
fn integer_literal(value : Json, keyword : String) -> Int64 raise SchemaIssue {
  let raw = match value {
    Number(_, repr=Some(raw)) => raw
    _ => raise Unsupported("\{keyword} requires an integer literal")
  }
  let number = @string.parse_int64(raw) catch {
    _ => raise Unsupported("\{keyword} requires an integer literal")
  }
  if number < -integer_literal_limit || number > integer_literal_limit {
    raise Unsupported("\{keyword} exceeds the exact integer range")
  }
  number
}

///|
fn nonnegative_length(
  value : Json,
  keyword : String,
) -> Int64 raise SchemaIssue {
  let length = integer_literal(value, keyword)
  if length < 0L {
    raise Unsupported("\{keyword} requires a nonnegative length")
  }
  length
}

///|
fn nonempty_array(
  value : Json,
  keyword : String,
) -> Array[Json] raise SchemaIssue {
  match value {
    Array(items) if !items.is_empty() => items
    _ => raise Unsupported("\{keyword} requires a nonempty array")
  }
}

///|
fn check_literal_keywords(fields : Map[String, Json]) -> Unit raise SchemaIssue {
  for key, value in fields {
    match key {
      "type" | "enum" | "const" => ()
      _ => check_annotation(key, value)
    }
  }
}

///|
fn literal_candidates(
  fields : Map[String, Json],
) -> Array[Json]? raise SchemaIssue {
  let constant = fields.get("const")
  match fields.get("enum") {
    Some(value) => {
      let members = nonempty_array(value, "enum")
      match constant {
        Some(value) => Some(if members.contains(value) { [value] } else { [] })
        None => Some(members)
      }
    }
    None => constant.map(value => [value])
  }
}

///|
let integer_work_limit : Int32 = 131072

///|
fn spend_integer_work(
  work : Ref[Int32],
  units : Int32,
) -> Unit raise SchemaIssue {
  if units > work.val {
    raise Unsupported("integer solver work limit exceeded")
  }
  work.val -= units
}

///|
fn intersect_integer_intervals(
  left : Array[Interval],
  right : Array[Interval],
  work : Ref[Int32],
) -> Array[Interval] raise SchemaIssue {
  spend_integer_work(work, left.length())
  spend_integer_work(work, right.length())
  intersect_intervals(left, right)
}

///|
fn integer_intervals(
  constraints : IntegerConstraints,
) -> Array[Interval] raise SchemaIssue {
  // Supported assertions treat each outer tail uniformly.
  let lower = constraints.lower.unwrap_or(-integer_literal_limit - 1L)
  let upper = constraints.upper.unwrap_or(integer_literal_limit + 1L)
  match constraints.values {
    Some(members) => {
      spend_integer_work(constraints.work, members.length())
      members.filter(interval => {
        lower <= interval.lower && interval.upper <= upper
      })
    }
    None if lower <= upper => [{ lower, upper, }]
    None => []
  }
}

///|
fn compile_integer_branch(
  value : Json,
  constraints : IntegerConstraints,
  depth : Int32,
) -> Array[Interval] raise SchemaIssue {
  spend_integer_work(constraints.work, 1)
  match value {
    False => []
    True => integer_intervals(constraints)
    Object(fields) => {
      match fields.get("type") {
        None
        | Some(String("integer" | "number"))
        | Some(Array([String("integer" | "number")])) => ()
        _ => raise Unsupported("integer branches must allow integers")
      }
      compile_integer(fields, constraints, depth)
    }
    _ => raise Unsupported("expected an integer subschema or boolean")
  }
}

///|
fn restrict_integer_values(
  inherited : Array[Interval]?,
  items : Array[Json],
  keyword : String,
  work : Ref[Int32],
) -> Array[Interval] raise SchemaIssue {
  spend_integer_work(work, items.length())
  let singletons = []
  for item in items {
    if item is Number(_, repr=_) {
      let value = integer_literal(item, keyword)
      singletons.push({ lower: value, upper: value, })
    }
  }
  match inherited {
    Some(values) => intersect_integer_intervals(values, singletons, work)
    None => singletons
  }
}

///|
fn compile_integer(
  fields : Map[String, Json],
  inherited : IntegerConstraints,
  depth : Int32,
) -> Array[Interval] raise SchemaIssue {
  if depth > 64 {
    raise Unsupported("integer schema exceeds the composition depth limit")
  }
  let mut lower = inherited.lower
  let mut upper = inherited.upper
  let mut values = inherited.values
  let work = inherited.work
  let mut branches = None
  let mut conjuncts = []
  for key, value in fields {
    match key {
      "type" => ()
      "minimum" | "exclusiveMinimum" => {
        let bound = integer_literal(value, key)
        let point = if key == "exclusiveMinimum" { bound + 1L } else { bound }
        lower = Some(point.max(lower.unwrap_or(point)))
      }
      "maximum" | "exclusiveMaximum" => {
        let bound = integer_literal(value, key)
        let point = if key == "exclusiveMaximum" { bound - 1L } else { bound }
        upper = Some(point.min(upper.unwrap_or(point)))
      }
      "enum" =>
        values = Some(
          restrict_integer_values(values, nonempty_array(value, key), key, work),
        )
      "const" =>
        values = Some(restrict_integer_values(values, [value], key, work))
      "anyOf" => branches = Some(nonempty_array(value, key))
      "allOf" => conjuncts = nonempty_array(value, key)
      _ => check_annotation(key, value)
    }
  }
  let constraints = { lower, upper, values, work, }
  let mut result = match branches {
    Some(items) => {
      let intervals = []
      for item in items {
        let branch = compile_integer_branch(item, constraints, depth + 1)
        spend_integer_work(work, branch.length())
        for interval in branch {
          intervals.push(interval)
        }
      }
      intervals
    }
    None => integer_intervals(constraints)
  }
  for item in conjuncts {
    result = intersect_integer_intervals(
      result,
      compile_integer_branch(item, constraints, depth + 1),
      work,
    )
  }
  result
}

///|
fn compile_boolean(fields : Map[String, Json]) -> Domain raise SchemaIssue {
  check_literal_keywords(fields)
  let choices = [false, true]
  match literal_candidates(fields) {
    None => Booleans(choices)
    Some(members) =>
      Booleans(choices.filter(value => members.contains(Json::boolean(value))))
  }
}

///|
fn null_matches_literals(fields : Map[String, Json]) -> Bool raise SchemaIssue {
  match literal_candidates(fields) {
    None => true
    Some(members) => members.contains(Json::null())
  }
}

///|
fn compile_non_null(
  kind : String,
  fields : Map[String, Json],
  depth : Int32,
  integer_work : Ref[Int32],
) -> NonNullDomain raise SchemaIssue {
  match kind {
    "integer" =>
      Scalar(
        Integers(
          compile_integer(
            fields,
            { lower: None, upper: None, values: None, work: integer_work, },
            0,
          ),
        ),
      )
    "number" => {
      for key, value in fields {
        if key != "type" {
          check_annotation(key, value)
        }
      }
      Scalar(Numbers)
    }
    "string" => Scalar(compile_string(fields))
    "boolean" => Scalar(compile_boolean(fields))
    "object" => Record(compile_object(fields, depth, integer_work))
    "array" => Sequence(compile_array(fields, depth, integer_work))
    _ => raise Unsupported("unsupported schema type: \{kind}")
  }
}

///|
fn compile_type_array(
  kinds : Array[Json],
  fields : Map[String, Json],
  depth : Int32,
  integer_work : Ref[Int32],
) -> CompiledSchema raise SchemaIssue {
  if kinds.is_empty() {
    raise Unsupported("type must contain at least one type name")
  }
  let mut non_null_type = None
  let mut includes_null = false
  for kind in kinds {
    match kind {
      String("null") if !includes_null => includes_null = true
      String("null") => raise Unsupported("type must contain unique type names")
      String(name) if non_null_type is None => non_null_type = Some(name)
      String(_) =>
        raise Unsupported("type arrays support at most one non-null type")
      _ => raise Unsupported("type must contain string type names")
    }
  }
  let non_null = match non_null_type {
    Some(name) => compile_non_null(name, fields, depth, integer_work)
    None => {
      check_literal_keywords(fields)
      NoNonNull
    }
  }
  let accepts_null = if includes_null {
    if fields.contains("anyOf") || fields.contains("allOf") {
      raise Unsupported("nullable types with composition are unsupported")
    }
    null_matches_literals(fields)
  } else {
    false
  }
  { non_null, accepts_null, }
}

///|
fn compile_shape(
  value : Json,
  depth : Int32,
  integer_work : Ref[Int32],
) -> CompiledSchema raise SchemaIssue {
  if depth > 64 {
    raise Unsupported("schema exceeds the nesting depth limit")
  }
  match value {
    True => all_values
    False => empty_value_set
    Object(fields) => {
      let kind = fields.get("type")
      if fields.get("oneOf") is Some(branches) {
        return compile_branch_composition(
          fields, branches, "oneOf", depth, integer_work,
        )
      }
      let integer = match kind {
        Some(String("integer") | Array([String("integer")])) => true
        _ => false
      }
      if !integer {
        if fields.get("anyOf") is Some(branches) {
          return compile_branch_composition(
            fields, branches, "anyOf", depth, integer_work,
          )
        }
        if fields.get("allOf") is Some(branches) {
          return compile_branch_composition(
            fields, branches, "allOf", depth, integer_work,
          )
        }
      }
      match kind {
        Some(String("null")) => {
          check_literal_keywords(fields)
          { non_null: NoNonNull, accepts_null: null_matches_literals(fields), }
        }
        Some(String(kind)) =>
          {
            non_null: compile_non_null(kind, fields, depth, integer_work),
            accepts_null: false,
          }
        Some(Array(kinds)) =>
          compile_type_array(kinds, fields, depth, integer_work)
        Some(_) =>
          raise Unsupported("type must be a string or array of type names")
        None => {
          for key, value in fields {
            check_annotation(key, value)
          }
          all_values
        }
      }
    }
    _ => raise Unsupported("expected a schema object or boolean")
  }
}

///|
fn compile_schema(
  value : Json,
  label : String,
) -> CompiledSchema raise SchemaIssue {
  compile_shape(value, 0, Ref(integer_work_limit)) catch {
    Unsupported(reason) => raise Unsupported("\{label}: \{reason}")
  }
}

///|
fn missing_scalar(
  source : Domain,
  target : Domain?,
) -> Witness? raise SchemaIssue {
  match source {
    Integers(source) => {
      let target = match target {
        Some(Integers(intervals)) => intervals
        Some(Numbers) => return None
        _ => []
      }
      first_uncovered(source, target).map(value => {
        Literal(Json::number(value.to_double()))
      })
    }
    Numbers =>
      if target is Some(Numbers) {
        None
      } else {
        Some(Literal(Json::number(0.5)))
      }
    Strings(source) => {
      let target = match target {
        Some(Strings(values)) => Some(values)
        _ => None
      }
      missing_string(source, target)
    }
    Booleans(source) => {
      let target = match target {
        Some(Booleans(values)) => values
        _ => []
      }
      for value in source {
        if !target.contains(value) {
          return Some(Literal(Json::boolean(value)))
        }
      }
      None
    }
  }
}

///|
fn has_value(schema : CompiledSchema) -> Bool {
  schema.accepts_null || has_non_null_value(schema.non_null)
}

///|
fn has_non_null_value(domain : NonNullDomain) -> Bool {
  match domain {
    AnyNonNull | Scalar(Numbers) | Alternatives(_) => true
    NoNonNull => false
    Scalar(Integers(intervals)) => !intervals.is_empty()
    Scalar(Strings(StringLengths(_))) => true
    Scalar(Strings(StringValues(strings))) => !strings.is_empty()
    Scalar(Booleans(values)) => !values.is_empty()
    Record(shape) => shape.inhabited
    Sequence(shape) => shape.inhabited
  }
}

///|
fn non_null_example(domain : NonNullDomain) -> Witness? {
  match domain {
    AnyNonNull => Some(Literal(Json::boolean(false)))
    NoNonNull => None
    Scalar(Integers([first, ..])) =>
      Some(Literal(Json::number(first.lower.to_double())))
    Scalar(Numbers) => Some(Literal(Json::number(0.5)))
    Scalar(Strings(domain)) => example_string(domain)
    Scalar(Booleans([first, ..])) => Some(Literal(Json::boolean(first)))
    Scalar(_) => None
    Record(shape) if shape.inhabited =>
      Some(ObjectWitness(shape, shape.minimum, None))
    Record(_) => None
    Sequence(shape) if shape.inhabited =>
      Some(ArrayWitness(shape, shape.minimum, None))
    Sequence(_) => None
    Alternatives(branches) => {
      let mut oversized = None
      for _, branch in branches {
        if non_null_example(branch) is Some(value) {
          if witness_size_floor(value) <= output_size_limit.to_int64() {
            return Some(value)
          }
          oversized = Some(value)
        }
      }
      oversized
    }
  }
}

///|
fn example_witness(schema : CompiledSchema) -> Witness? {
  if schema.accepts_null {
    Some(Literal(Json::null()))
  } else {
    non_null_example(schema.non_null)
  }
}

///|
let comparison_work_limit : Int32 = 262144

///|
fn spend_comparison_work(
  work : Ref[Int32],
  units : Int32,
) -> Unit raise SchemaIssue {
  if units > work.val {
    raise Unsupported("solver comparison work limit exceeded")
  }
  work.val -= units
}

///|
fn spend_scalar_work(
  work : Ref[Int32],
  domain : Domain,
) -> Unit raise SchemaIssue {
  match domain {
    Integers(intervals) => spend_comparison_work(work, intervals.length())
    Booleans(values) => spend_comparison_work(work, values.length())
    Numbers | Strings(StringLengths(_)) => spend_comparison_work(work, 1)
    Strings(StringValues(values)) => {
      spend_comparison_work(work, values.length())
      for value in values {
        spend_comparison_work(work, value.length() / 16)
      }
    }
  }
}

///|
fn find_witness(
  source : CompiledSchema,
  target : CompiledSchema,
  work : Ref[Int32],
) -> Witness? raise SchemaIssue {
  if source.accepts_null && !target.accepts_null {
    return Some(Literal(Json::null()))
  }
  find_non_null_witness(source.non_null, target.non_null, work)
}

///|
fn find_non_null_witness(
  source : NonNullDomain,
  target : NonNullDomain,
  work : Ref[Int32],
) -> Witness? raise SchemaIssue {
  match (source, target) {
    (NoNonNull, _) | (_, AnyNonNull) => None
    (AnyNonNull, NoNonNull) => Some(Literal(Json::boolean(false)))
    (AnyNonNull, Alternatives(_)) => {
      // A union can cover all JSON types while tightening one of them.
      let unrestricted : Map[String, NonNullDomain] = Map([])
      let compile_work = Ref(integer_work_limit)
      for kind in ["number", "string", "boolean", "object", "array"] {
        unrestricted[kind] = compile_non_null(kind, Map([]), 0, compile_work)
      }
      find_non_null_witness(Alternatives(unrestricted), target, work)
    }
    (AnyNonNull, Record(_) | Sequence(_)) => Some(Literal(Json::string("")))
    (AnyNonNull, Scalar(_)) => Some(Literal(Json::empty_object()))
    (Alternatives(branches), _) => {
      let mut oversized = None
      for _, branch in branches {
        spend_comparison_work(work, 1)
        if find_non_null_witness(branch, target, work) is Some(value) {
          if witness_size_floor(value) <= output_size_limit.to_int64() {
            return Some(value)
          }
          oversized = Some(value)
        }
      }
      oversized
    }
    (_, Alternatives(branches)) => {
      let target = match single_domain_kind(source) {
        Some(kind) => branch_for_kind(branches, kind)
        None => NoNonNull
      }
      find_non_null_witness(source, target, work)
    }
    (Scalar(source), Scalar(target)) => {
      spend_scalar_work(work, source)
      spend_scalar_work(work, target)
      missing_scalar(source, Some(target))
    }
    (Record(source), Record(target)) => object_witness(source, target, work)
    (Sequence(source), Sequence(target)) => array_witness(source, target, work)
    (source, _) => non_null_example(source)
  }
}

///|
let output_size_limit : Int32 = 65536

///|
fn witness_size_floor(witness : Witness) -> Int64 {
  match witness {
    Literal(String(text)) => 1L + text.length().to_int64()
    Literal(_) => 1L
    StringWitness(length, first) => 1L + string_witness_units(length, first)
    ObjectWitness(_, length, Some(Include(name, value))) =>
      length + name.length().to_int64() + witness_size_floor(value)
    ObjectWitness(_, length, _) => 1L + length
    ArrayWitness(_, length, replacement) =>
      1L +
      length +
      replacement.map(pair => witness_size_floor(pair.1) - 1L).unwrap_or(0L)
  }
}

///|
fn spend_output_budget(
  budget : Ref[Int32],
  units : Int32,
) -> Unit raise SchemaIssue {
  if units > budget.val {
    raise Unsupported("counterexample exceeds the output size limit")
  }
  budget.val -= units
}

///|
fn render_witness(
  witness : Witness,
  budget : Ref[Int32],
) -> Json raise SchemaIssue {
  spend_output_budget(budget, 1)
  match witness {
    Literal(String(text)) => {
      spend_output_budget(budget, text.length())
      Json::string(text)
    }
    Literal(value) => value
    StringWitness(length, first) => render_string(length, first, budget)
    ObjectWitness(shape, length, change) =>
      render_object(shape, length, change, budget)
    ArrayWitness(shape, length, replacement) =>
      render_array(shape, length, replacement, budget)
  }
}

///|
fn compare_values(source : Json, target : Json) -> Verdict raise SchemaIssue {
  let source = compile_schema(source, "source")
  let target = compile_schema(target, "target")
  match find_witness(source, target, Ref(comparison_work_limit)) {
    Some(value) => Incompatible(render_witness(value, Ref(output_size_limit)))
    None => Compatible
  }
}

///|
fn compare_values_report(
  source : Json,
  target : Json,
  include_diagnostic : Bool,
) -> ComparisonReport raise SchemaIssue {
  let verdict = compare_values(source, target)
  let diagnostic = if include_diagnostic && verdict is Incompatible(witness) {
    diagnose_rejection(target, witness)
  } else {
    None
  }
  { verdict, diagnostic, }
}

///|
fn compare_schema_report(
  source : String,
  target : String,
  include_diagnostic : Bool,
) -> ComparisonReport {
  compare_values_report(
    parse_document(source, "source"),
    parse_document(target, "target"),
    include_diagnostic,
  ) catch {
    Unsupported(reason) => { verdict: Unknown(reason), diagnostic: None, }
  }
}

///|
/// Check inclusion for two standalone JSON Schema documents.
pub fn compare_schemas(source : String, target : String) -> Verdict {
  compare_schema_report(source, target, false).verdict
}

///|
/// Compare standalone schemas and locate a failing rule in the target.
pub fn compare_schemas_detailed(
  source : String,
  target : String,
) -> ComparisonReport {
  compare_schema_report(source, target, true)
}