///|
priv struct Batch {
  jobs : Array[Job]
  mut estimate : Int32
}

///|
fn group_jobs(jobs : Array[Job], default_duration : Int32) -> Array[Batch] {
  let groups : Map[String, Batch] = Map([])
  let batches : Array[Batch] = []
  for job in jobs {
    let estimate = job.duration_ms.unwrap_or(default_duration)
    if job.group is Some(name) && groups.get(name) is Some(batch) {
      batch.jobs.push(job)
      batch.estimate += estimate
    } else {
      let batch : Batch = { jobs: [job], estimate, }
      batches.push(batch)
      if job.group is Some(name) {
        groups[name] = batch
      }
    }
  }
  batches
}

///|
priv struct Placement {
  batch : Batch
  eligible : Array[Int32]
  mask : UInt32
}

///|
fn placements(
  batches : Array[Batch],
  workers : Array[Worker],
) -> Array[Placement] raise PlanError {
  // A worker occupies one bit. A batch must satisfy every job's labels.
  let label_workers : Map[String, UInt32] = Map([])
  let mut all_workers = 0U
  for i, worker in workers {
    let bit = 1U << i
    all_workers = all_workers | bit
    for label in worker.labels {
      label_workers[label] = label_workers.get(label).unwrap_or(0U) | bit
    }
  }
  let result : Array[Placement] = []
  for batch in batches {
    let mut mask = all_workers
    for job in batch.jobs {
      for label in job.requires {
        mask = mask & label_workers.get(label).unwrap_or(0U)
      }
    }
    if mask == 0U {
      let first = batch.jobs[0]
      let label = match first.group {
        Some(group) => "group " + group
        None => "job " + first.id
      }
      raise PlanError("no eligible worker for " + label)
    }
    let eligible : Array[Int32] = []
    for i in 0.. {
    let limit = a.eligible.length().compare(b.eligible.length())
    if limit != 0 {
      return limit
    }
    let duration = b.batch.estimate.compare(a.batch.estimate)
    if duration != 0 {
      return duration
    }
    a.batch.jobs[0].id.compare(b.batch.jobs[0].id)
  })
  result
}

///|
fn eligibility_bound(options : Array[Placement]) -> Int32 {
  // All work whose eligible workers are a subset of these workers must fit here.
  let counts : Map[UInt32, Int32] = Map([])
  let workloads : Map[UInt32, Int32] = Map([])
  for option in options {
    let mask = option.mask
    counts[mask] = option.eligible.length()
    workloads[mask] = workloads.get(mask).unwrap_or(0) + option.batch.estimate
  }
  let mut lower = 0
  for mask in counts.keys() {
    let mut work = 0
    for candidate in workloads.keys() {
      if (candidate & mask) == candidate {
        work += workloads[candidate]
      }
    }
    let n = counts[mask]
    lower = lower.max((work + n - 1) / n)
  }
  lower
}

///|
fn assign(
  options : Array[Placement],
  workers : Array[Worker],
) -> (Array[Shard], Int32) {
  let assignments : Array[Array[String]] = Array::makei(workers.length(), _ => {
    []
  })
  let loads = Array::make(workers.length(), 0)
  for option in options {
    let estimate = option.batch.estimate
    let mut best = option.eligible[0]
    for index in option.eligible {
      if loads[index] < loads[best] {
        best = index
      }
    }
    loads[best] += estimate
    for job in option.batch.jobs {
      assignments[best].push(job.id)
    }
  }
  let mut makespan = 0
  let shards = workers.mapi((i, worker) => {
    makespan = makespan.max(loads[i])
    { worker: worker.id, jobs: assignments[i], estimated_ms: loads[i], }
  })
  (shards, makespan)
}

///|
/// Select the better of two deterministic orders when capabilities differ.
pub fn plan(request : Request) -> Plan raise PlanError {
  validate(request)
  let jobs = request.jobs.copy()
  let workers = request.workers.copy()
  jobs.sort_by_key(job => job.id)
  workers.sort_by_key(worker => worker.id)
  let batches = group_jobs(jobs, request.default_duration_ms)
  let options = placements(batches, workers)
  let mut total = 0
  let mut largest = 0
  for option in options {
    total += option.batch.estimate
    largest = largest.max(option.batch.estimate)
  }
  let lower = largest
    .max((total + workers.length() - 1) / workers.length())
    .max(eligibility_bound(options))
  let first = assign(options, workers)
  let (shards, makespan) = if first.1 > lower &&
    options.length() > 1 &&
    options[0].eligible.length() !=
    options[options.length() - 1].eligible.length() {
    options.sort_by((a, b) => {
      let duration = b.batch.estimate.compare(a.batch.estimate)
      if duration != 0 {
        duration
      } else {
        a.batch.jobs[0].id.compare(b.batch.jobs[0].id)
      }
    })
    let alternative = assign(options, workers)
    if alternative.1 < first.1 {
      alternative
    } else {
      first
    }
  } else {
    first
  }
  {
    shards,
    estimated_jobs: jobs
    .filter(job => job.duration_ms is None)
    .map(job => job.id),
    makespan_ms: makespan,
    lower_bound_ms: lower,
    within_budget: request.budget_ms.map(budget => makespan <= budget),
  }
}