///|
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]
}

///|
fn placements(
  batches : Array[Batch],
  workers : Array[Worker],
) -> Array[Placement] raise PlanError {
  let result : Array[Placement] = []
  for batch in batches {
    let eligible : Array[Int32] = []
    for i, worker in workers {
      if batch.jobs.all(job => {
          job.requires.all(label => worker.labels.contains(label))
        }) {
        eligible.push(i)
      }
    }
    if eligible.is_empty() {
      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)
    }
    result.push({ batch, eligible, })
  }
  result.sort_by((a, b) => {
    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 mut mask = 0U
    for i in option.eligible {
      mask = mask | (1U << i)
    }
    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),
  }
}