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

///|
priv enum Domain {
  Integer(Int32, Int32)
  Text(Array[String]?)
  Flag
}

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

///|
pub struct Contract {
  priv fields : Map[String, Field]
  priv names : Array[String]
  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 => false
    Some(v) if v == Json::boolean(true) => true
    Some(v) if v == Json::boolean(false) => false
    _ => raise ContractError(label + " must be boolean")
  }
}

///|
fn integer_value(value : Json) -> Int32? {
  guard value is Number(n, repr~) &&
    n >= -1000000.0 &&
    n <= 1000000.0 &&
    n == n.floor() else {
    return None
  }
  let i = n.to_int()
  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?) -> Array[String]? 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 result : Array[String] = []
  for value in values {
    guard value is String(s) && s.length() <= 128 && !result.contains(s) else {
      raise ContractError(
        "allowed strings must be unique and at most 128 UTF-16 units",
      )
    }
    result.push(s)
  }
  result.sort()
  Some(result)
}

///|
fn decode_field(value : Json) -> Field raise ContractError {
  let obj = object(value, "field")
  let domain = match obj.get("type") {
    Some(String("int")) => {
      keys(obj, ["type", "required", "min", "max"])
      let low = integer_bound(obj.get("min"), -1000000)
      let high = integer_bound(obj.get("max"), 1000000)
      if low > high {
        raise ContractError("minimum exceeds maximum")
      }
      Integer(low, high)
    }
    Some(String("string")) => {
      keys(obj, ["type", "required", "allowed"])
      Text(enum_values(obj.get("allowed")))
    }
    Some(String("bool")) => {
      keys(obj, ["type", "required"])
      Flag
    }
    _ => raise ContractError("unknown field type")
  }
  { required: boolean_option(obj.get("required"), "required"), 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()
  for name in names {
    fields[name] = decode_field(declarations[name]) catch {
      ContractError(message) => raise ContractError(name + ": " + message)
    }
  }
  { fields, names, open: boolean_option(obj.get("open"), "open"), }
}

///|
fn accepts(domain : Domain, value : Json) -> Bool {
  match domain {
    Integer(low, high) =>
      integer_value(value) is Some(n) && n >= low && n <= high
    Text(allowed) =>
      value is String(s) && (allowed is None || allowed.unwrap().contains(s))
    Flag => value == Json::boolean(false) || value == Json::boolean(true)
  }
}

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

///|
pub fn validate(contract : Contract, record : Json) -> Array[Violation] {
  guard record is Object(values) else {
    return [{ field: "", reason: "record_must_be_object", }]
  }
  let violations : Array[Violation] = []
  for name in contract.names {
    let field = contract.fields[name]
    match values.get(name) {
      None if field.required =>
        violations.push({ field: name, reason: "required", })
      Some(value) if !accepts(field.domain, value) =>
        violations.push({ field: name, reason: "value_outside_domain", })
      _ => ()
    }
  }
  if !contract.open {
    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
}