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

///|
pub(all) struct Job {
  id : String
  duration_ms : Int32?
  group : String?
  requires : Array[String]
}

///|
pub(all) struct Worker {
  id : String
  labels : Array[String]
}

///|
pub(all) struct Request {
  jobs : Array[Job]
  workers : Array[Worker]
  default_duration_ms : Int32
  budget_ms : Int32?
}

///|
pub(all) struct Shard {
  worker : String
  jobs : Array[String]
  estimated_ms : Int32
}

///|
pub(all) struct Plan {
  shards : Array[Shard]
  estimated_jobs : Array[String]
  makespan_ms : Int32
  lower_bound_ms : Int32
  within_budget : Bool?
}

///|
fn duration_ok(n : Int32) -> Bool {
  n >= 1 && n <= 1000000
}

///|
fn valid_name(name : String) -> Bool {
  name.length() >= 1 && name.length() <= 128
}

///|
fn require_unique(
  seen : Map[String, Bool],
  name : String,
  kind : String,
) -> Unit raise PlanError {
  if !valid_name(name) || seen.contains(name) {
    raise PlanError("invalid or duplicate " + kind + ": " + name)
  }
  seen[name] = true
}

///|
fn validate_labels(
  labels : Array[String],
  kind : String,
) -> Unit raise PlanError {
  let count = labels.length()
  if count > 16 {
    raise PlanError(kind + " accepts at most 16 labels")
  }
  if count <= 1 {
    // No duplicate is possible, but the single label still needs validation.
    if count == 1 && !valid_name(labels[0]) {
      raise PlanError("invalid or duplicate " + kind + ": " + labels[0])
    }
    return
  }
  let seen : Map[String, Bool] = Map([])
  for name in labels {
    require_unique(seen, name, kind)
  }
}

///|
fn validate(request : Request) -> Unit raise PlanError {
  if request.jobs.length() > 1024 ||
    request.workers.length() < 1 ||
    request.workers.length() > 32 {
    raise PlanError("require 0..1024 jobs and 1..32 workers")
  }
  if !duration_ok(request.default_duration_ms) {
    raise PlanError("invalid default duration")
  }
  if request.budget_ms is Some(budget) && (budget < 0 || budget > 1024000000) {
    raise PlanError("invalid budget")
  }
  let workers : Map[String, Bool] = Map([])
  let jobs : Map[String, Bool] = Map([])
  for worker in request.workers {
    require_unique(workers, worker.id, "worker")
    validate_labels(worker.labels, "worker label")
  }
  for job in request.jobs {
    require_unique(jobs, job.id, "job")
    if job.duration_ms is Some(n) && !duration_ok(n) {
      raise PlanError("invalid duration: " + job.id)
    }
    if job.group is Some(g) && !valid_name(g) {
      raise PlanError("invalid group: " + job.id)
    }
    validate_labels(job.requires, "required label")
  }
}