///|
const DOCUMENT_LIMIT : Int32 = 1048576

///|
fn parse_document(text : String) -> Json raise InputError {
  if text.length() > DOCUMENT_LIMIT {
    raise Invalid("JSON exceeds 1048576 code units")
  }
  check_document_depth(text)
  @json.parse(text, reject_duplicate_keys=true, preserve_number_repr=true) catch {
    e => raise Invalid("JSON syntax: " + e.to_string())
  }
}

///|
fn object_fields(
  value : Json,
  keys : Array[String],
  context : String,
) -> Map[String, Json] raise InputError {
  guard value is Object(fields) else {
    raise Invalid(context + " must be an object")
  }
  if fields.length() != keys.length() {
    raise Invalid(context + " has missing or unknown fields")
  }
  for key in keys {
    if fields.get(key) is None {
      raise Invalid(context + " is missing " + key)
    }
  }
  fields
}

///|
fn list(
  value : Json,
  max : Int32,
  context : String,
) -> Array[Json] raise InputError {
  guard value is Array(items) && items.length() <= max else {
    raise Invalid("\{context} must be an array of at most \{max} elements")
  }
  items
}

///|
fn check_number(value : Json, context : String) -> Unit raise InputError {
  if value is Number(n, repr=Some(token)) &&
    !token.contains_char('.') &&
    !token.contains_char('e') &&
    !token.contains_char('E') &&
    n >= -2147483648.0 &&
    n <= 2147483647.0 {
    return
  }
  raise Invalid(context + " must be an Int32 integer token")
}

///|
fn check_numbers(
  value : Json,
  max : Int32,
  context : String,
) -> Unit raise InputError {
  for x in list(value, max, context) {
    check_number(x, context)
  }
}

///|
fn check_schema(value : Json) -> Unit raise InputError {
  check_number(value, "schema")
  guard value is Number(1.0, ..) else { raise Invalid("expected schema 1") }
}

///|
/// Decode a schema 1 input. Unknown fields and duplicate keys are errors.
pub fn decode_shift(text : String) -> Shift raise InputError {
  let value = parse_document(text)
  let doc = object_fields(
    value,
    ["schema", "slots", "blocked", "feeders", "initial", "jobs"],
    "shift",
  )
  check_schema(doc["schema"])
  check_number(doc["slots"], "slots")
  check_numbers(doc["blocked"], 64, "blocked")
  check_numbers(doc["initial"], 32, "initial")
  for item in list(doc["feeders"], 32, "feeders") {
    let f = object_fields(
      item,
      ["id", "width", "starts", "load", "unload", "locked"],
      "feeder",
    )
    check_number(f["width"], "width")
    check_number(f["load"], "load")
    check_number(f["unload"], "unload")
    check_numbers(f["starts"], 64, "starts")
  }
  for item in list(doc["jobs"], 64, "jobs") {
    let j = object_fields(item, ["id", "need"], "job")
    ignore(list(j["need"], 32, "need"))
  }
  let s : Shift = @json.from_json(value) catch {
    e => raise Invalid("shift field type: " + e.to_string())
  }
  validate(s)
  s
}

///|
/// Decode the output of encode_plan or an operator-edited sheet.
pub fn decode_plan(text : String) -> Plan raise InputError {
  let value = parse_document(text)
  let doc = object_fields(value, ["schema", "steps", "cost"], "plan")
  check_schema(doc["schema"])
  check_number(doc["cost"], "total cost")
  for item in list(doc["steps"], 64, "steps") {
    let step = object_fields(
      item,
      ["job", "positions", "actions", "cost"],
      "step",
    )
    check_numbers(step["positions"], 32, "positions")
    check_number(step["cost"], "step cost")
    for a in list(step["actions"], 64, "actions") {
      let operation = object_fields(a, ["kind", "feeder", "slot"], "action")
      check_number(operation["slot"], "slot")
    }
  }
  @json.from_json(value) catch {
    e => raise Invalid("plan field type: " + e.to_string())
  }
}

///|
/// Produce the schema 1 JSON representation for sharing and replay.
pub fn encode_plan(plan : Plan) -> Json {
  { "schema": Json(1), "steps": Json(plan.steps), "cost": Json(plan.cost) }
}