///|
pub(all) suberror ContractError {
  ContractError(String)
}

///|
priv struct EnumValues {
  sorted : Array[String]
  members : Map[String, Bool]
}

///|
priv enum Domain {
  Integer(Int32, Int32)
  Text(EnumValues?)
  Flag
}

///|
priv struct Field {
  required : Bool
  nullable : Bool
  domain : Domain
}

///|
pub struct Contract {
  priv fields : Map[String, Field]
  priv ordered : Array[(String, Field)]
  priv required_fields : Array[(String, Field)]
  priv open : Bool
}

///|
fn object(
  value : Json,
  label : String,
) -> Map[String, Json] raise ContractError {
  guard value is Object(fields) else {
    raise ContractError(label + " must be an object")
  }
  fields
}

///|
fn keys(
  fields : Map[String, Json],
  allowed : Array[String],
) -> Unit raise ContractError {
  for key in fields.keys() {
    if !allowed.contains(key) {
      raise ContractError("unknown key " + key)
    }
  }
}

///|
fn boolean_option(value : Json?, label : String) -> Bool raise ContractError {
  match value {
    None | Some(False) => false
    Some(True) => true
    _ => raise ContractError(label + " must be boolean")
  }
}

///|
fn integer_value(
  value : Json,
  low~ : Int32 = -1000000,
  high~ : Int32 = 1000000,
) -> Int32? {
  guard value is Number(n, repr~) &&
    n >= low.to_double() &&
    n <= high.to_double() else {
    return None
  }
  // The bounds fit in Int32, so an exact round trip rules out fractions.
  let i = n.to_int()
  if n != i.to_double() {
    return None
  }
  if repr is Some(s) && s != i.to_string() && !(i == 0 && s == "-0") {
    return None
  }
  Some(i)
}

///|
fn integer_bound(value : Json?, fallback : Int32) -> Int32 raise ContractError {
  match value {
    None => fallback
    Some(n) => {
      guard integer_value(n) is Some(i) else {
        raise ContractError("expected an integer in -1000000..1000000")
      }
      i
    }
  }
}

///|
fn enum_values(value : Json?) -> EnumValues? raise ContractError {
  guard value is Some(raw) else { return None }
  guard raw is Array(values) && values.length() >= 1 && values.length() <= 32 else {
    raise ContractError("allowed must contain 1..32 strings")
  }
  let sorted : Array[String] = []
  let members : Map[String, Bool] = Map([])
  for value in values {
    guard value is String(s) && s.length() <= 128 && !members.contains(s) else {
      raise ContractError(
        "allowed strings must be unique and at most 128 UTF-16 units",
      )
    }
    sorted.push(s)
    members[s] = true
  }
  sorted.sort()
  Some({ sorted, members, })
}

///|
fn decode_field(value : Json) -> Field raise ContractError {
  let obj = object(value, "field")
  let kind = match obj.get("type") {
    Some(String(kind)) if kind == "int" || kind == "string" || kind == "bool" =>
      kind
    _ => raise ContractError("unknown field type")
  }
  let mut minimum : Json? = None
  let mut maximum : Json? = None
  let mut allowed : Json? = None
  let mut required : Json? = None
  let mut nullable : Json? = None
  // Keep raw values until every key has been checked, so unknown keys are
  // still reported before invalid values on recognized properties.
  for key, raw in obj {
    match key {
      "type" => ()
      "required" => required = Some(raw)
      "nullable" => nullable = Some(raw)
      "min" if kind == "int" => minimum = Some(raw)
      "max" if kind == "int" => maximum = Some(raw)
      "allowed" if kind == "string" => allowed = Some(raw)
      _ => raise ContractError("unknown key " + key)
    }
  }
  let domain = match kind {
    "int" => {
      let low = integer_bound(minimum, -1000000)
      let high = integer_bound(maximum, 1000000)
      if low > high {
        raise ContractError("minimum exceeds maximum")
      }
      Integer(low, high)
    }
    "string" => Text(enum_values(allowed))
    _ => Flag
  }
  {
    required: boolean_option(required, "required"),
    nullable: boolean_option(nullable, "nullable"),
    domain,
  }
}

///|
pub fn parse_json(source : String) -> Json raise ContractError {
  if source.length() > 1048576 {
    raise ContractError("JSON input exceeds 1 Mi UTF-16 units")
  }
  @json.parse(
    source,
    max_nesting_depth=24,
    reject_duplicate_keys=true,
    preserve_number_repr=true,
  ) catch {
    _ => raise ContractError("invalid JSON text")
  }
}

///|
pub fn parse_contract(value : Json) -> Contract raise ContractError {
  let obj = object(value, "contract")
  keys(obj, ["fields", "open"])
  guard obj.get("fields") is Some(Object(declarations)) &&
    declarations.length() <= 64 else {
    raise ContractError("fields must be an object containing at most 64 fields")
  }
  let fields : Map[String, Field] = Map([])
  let names : Array[String] = []
  for name in declarations.keys() {
    if name.length() == 0 || name.length() > 64 {
      raise ContractError("field names must contain 1..64 UTF-16 units")
    }
    names.push(name)
  }
  names.sort()
  let ordered = names.map(name => {
    let field = decode_field(declarations[name]) catch {
      ContractError(message) => raise ContractError(name + ": " + message)
    }
    fields[name] = field
    (name, field)
  })
  let required_fields = ordered.filter(entry => entry.1.required)
  {
    fields,
    ordered,
    required_fields,
    open: boolean_option(obj.get("open"), "open"),
  }
}

///|
fn accepts(domain : Domain, value : Json) -> Bool {
  match domain {
    Integer(low, high) => integer_value(value, low~, high~) is Some(_)
    Text(None) => value is String(_)
    Text(Some(allowed)) => value is String(s) && allowed.members.contains(s)
    Flag => value is (True | False)
  }
}

///|
fn accepts_value(field : Field, value : Json) -> Bool {
  if value is Null {
    field.nullable
  } else {
    accepts(field.domain, value)
  }
}

///|
pub(all) struct Violation {
  field : String
  reason : String
}

///|
fn validate_record_fields(
  contract : Contract,
  values : Map[String, Json],
) -> Array[Violation] {
  let violations : Array[Violation] = []
  for (name, _) in contract.required_fields {
    if !values.contains(name) {
      violations.push({ field: name, reason: "required", })
    }
  }
  let extra : Array[String] = []
  for name, value in values {
    match contract.fields.get(name) {
      Some(field) if !accepts_value(field, value) =>
        violations.push({ field: name, reason: "value_outside_domain", })
      None if !contract.open => extra.push(name)
      _ => ()
    }
  }
  // Match the public order of the schema walk, then append unknown fields.
  violations.sort_by_key(violation => violation.field)
  extra.sort()
  for name in extra {
    violations.push({ field: name, reason: "unknown_field", })
  }
  violations
}

///|
pub fn validate(contract : Contract, record : Json) -> Array[Violation] {
  guard record is Object(values) else {
    return [{ field: "", reason: "record_must_be_object", }]
  }
  let declared = contract.ordered.length()
  let required = contract.required_fields.length()
  let count = values.length()
  // More keys than declarations guarantee an extra field in a closed record.
  // Scan record fields directly when that avoids walking the full schema.
  if count <= declared / 2 - required ||
    (!contract.open && count > declared && required <= declared / 2) {
    return validate_record_fields(contract, values)
  }
  let violations : Array[Violation] = []
  let mut known = 0
  for (name, field) in contract.ordered {
    match values.get(name) {
      None if field.required =>
        violations.push({ field: name, reason: "required", })
      Some(value) => {
        known += 1
        if !accepts_value(field, value) {
          violations.push({ field: name, reason: "value_outside_domain", })
        }
      }
      None => ()
    }
  }
  if !contract.open && known < values.length() {
    let extra : Array[String] = []
    for name in values.keys() {
      if !contract.fields.contains(name) {
        extra.push(name)
      }
    }
    extra.sort()
    for name in extra {
      violations.push({ field: name, reason: "unknown_field", })
    }
  }
  violations
}