///|
fn object(
  value : Json,
  kind : String,
  allowed : Array[String],
) -> Map[String, Json] raise PlanError {
  guard value is Object(obj) else {
    raise PlanError(kind + " must be an object")
  }
  for key in obj.keys() {
    if !allowed.contains(key) {
      raise PlanError("unknown " + kind + " field: " + key)
    }
  }
  obj
}

///|
fn text(value : Json?, field : String) -> String raise PlanError {
  guard value is Some(String(s)) && valid_name(s) else {
    raise PlanError(field + " must be a string of 1..128 UTF-16 units")
  }
  s
}

///|
fn optional_int(value : Json?, field : String) -> Int32? raise PlanError {
  if value is None {
    return None
  }
  guard value is Some(Number(n, repr~)) &&
    n >= 0.0 &&
    n <= 1024000000.0 &&
    n == n.floor() else {
    raise PlanError(field + " must be a nonnegative integer")
  }
  let result = n.to_int()
  if repr is Some(s) && s != result.to_string() && !(result == 0 && s == "-0") {
    raise PlanError(field + " must use a plain integer spelling")
  }
  Some(result)
}

///|
fn labels(value : Json?, field : String) -> Array[String] raise PlanError {
  if value is None {
    return []
  }
  guard value is Some(Array(xs)) && xs.length() <= 16 else {
    raise PlanError(field + " must be an array of at most 16 labels")
  }
  xs.map(x => text(Some(x), field))
}

///|
fn job_from_json(
  value : Json,
  timing : Map[String, Int32]?,
) -> Job raise PlanError {
  let obj = object(value, "job", ["id", "duration_ms", "group", "requires"])
  let group = obj.get("group").map(value => text(Some(value), "group"))
  let id = text(obj.get("id"), "job id")
  let estimate = match timing {
    Some(estimates) => estimates.get(id)
    None => None
  }
  let original = obj.get("duration_ms")
  // The history adapter has always filled a measured null duration.
  let duration = if estimate is Some(_) && original is Some(Null) {
    None
  } else {
    optional_int(original, "duration_ms")
  }
  if estimate is Some(_) && duration is Some(n) && !duration_ok(n) {
    raise PlanError("invalid duration: " + id)
  }
  {
    id,
    duration_ms: if estimate is Some(_) {
      estimate
    } else {
      duration
    },
    group,
    requires: labels(obj.get("requires"), "requires"),
  }
}

///|
fn worker_from_json(value : Json) -> Worker raise PlanError {
  let obj = object(value, "worker", ["id", "labels"])
  {
    id: text(obj.get("id"), "worker id"),
    labels: labels(obj.get("labels"), "labels"),
  }
}

///|
pub fn parse_json(source : String) -> Json raise PlanError {
  if source.length() > 1048576 {
    raise PlanError("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 PlanError("invalid JSON text")
  }
}

///|
fn read_request_impl(
  value : Json,
  timing : Map[String, Int32]?,
) -> Request raise PlanError {
  let obj = object(value, "request", [
    "jobs", "workers", "default_duration_ms", "budget_ms",
  ])
  guard obj.get("jobs") is Some(Array(jobs)) &&
    jobs.length() <= 1024 &&
    obj.get("workers") is Some(Array(workers)) &&
    workers.length() >= 1 &&
    workers.length() <= 32 else {
    raise PlanError("require 0..1024 jobs and 1..32 workers")
  }
  {
    jobs: jobs.map(job => job_from_json(job, timing)),
    workers: workers.map(worker_from_json),
    default_duration_ms: optional_int(
      obj.get("default_duration_ms"),
      "default_duration_ms",
    ).unwrap_or(1000),
    budget_ms: optional_int(obj.get("budget_ms"), "budget_ms"),
  }
}

///|
pub fn read_request(value : Json) -> Request raise PlanError {
  read_request_impl(value, None)
}

///|
/// Read a request and apply measured estimates without re-encoding its JSON.
pub fn read_request_with_timing(
  value : Json,
  timing : Json,
) -> Request raise PlanError {
  guard timing is Object(entries) && entries.length() <= 1024 else {
    raise PlanError("timing estimates must be a job-to-duration object")
  }
  let estimates : Map[String, Int32] = Map([])
  for id, value in entries {
    guard valid_name(id) &&
      optional_int(Some(value), "timing estimate") is Some(duration) &&
      duration_ok(duration) else {
      raise PlanError("invalid timing estimate: " + id)
    }
    estimates[id] = duration
  }
  let request = read_request_impl(value, Some(estimates))
  for job in request.jobs {
    estimates.remove(job.id)
  }
  if estimates.length() != 0 {
    raise PlanError("unknown job in timing estimates")
  }
  request
}

///|
fn count(n : Int32) -> Json {
  Json::number(n.to_double())
}

///|
pub fn report(value : Plan) -> Json {
  let shards = value.shards.map(shard => {
    Json::object(
      Map([
        ("worker", Json::string(shard.worker)),
        ("jobs", Json::array(shard.jobs.map(Json::string))),
        ("estimated_ms", count(shard.estimated_ms)),
      ]),
    )
  })
  Json::object(
    Map([
      ("shards", Json::array(shards)),
      ("estimated_jobs", Json::array(value.estimated_jobs.map(Json::string))),
      ("makespan_ms", count(value.makespan_ms)),
      ("lower_bound_ms", count(value.lower_bound_ms)),
      (
        "within_budget",
        value.within_budget.map(Json::boolean).unwrap_or(Json::null()),
      ),
    ]),
  )
}