///|
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 work_bound(mask : UInt32, workloads : Map[UInt32, Int32]) -> Int32 {
  let mut work = 0
  for candidate in workloads.keys() {
    if (candidate & mask) == candidate {
      work += workloads[candidate]
    }
  }
  let count = mask.popcnt()
  (work + count - 1) / count
}

///|
fn eligibility_bound(options : Array[Placement], worker_count : Int32) -> Int32 {
  let workloads : Map[UInt32, Int32] = Map([])
  for option in options {
    let mask = option.mask
    workloads[mask] = workloads.get(mask).unwrap_or(0) + option.batch.estimate
  }
  let pools : Array[UInt32] = []
  let constrained : Array[UInt32] = []
  let mut lower = 0
  for mask in workloads.keys() {
    lower = lower.max(work_bound(mask, workloads))
    // Fully flexible work can run outside any constrained pool.
    if mask.popcnt() == worker_count {
      continue
    }
    // A singleton cannot overlap another mask without being a subset.
    if mask.popcnt() > 1 {
      constrained.push(mask)
    }
    let mut merged = mask
    let mut i = 0
    while i < pools.length() {
      if (pools[i] & merged) == 0U {
        i += 1
      } else {
        merged = merged | pools.remove(i)
      }
    }
    pools.push(merged)
  }
  for mask in pools {
    lower = lower.max(work_bound(mask, workloads))
  }
  // A light batch can connect a busy subpool to an otherwise idle runner.
  // Check overlapping mask pairs as well as the fully connected pools.
  let checked : Map[UInt32, Bool] = Map([])
  let mut remaining_pairs = 512
  for i, left in constrained {
    for j in (i + 1).. Schedule {
  let worker_of : Array[Int32] = []
  let loads = Array::make(worker_count, 0)
  let mut makespan = 0
  for option in options {
    let mut best = option.eligible[0]
    for index in option.eligible {
      if loads[index] < loads[best] {
        best = index
      }
    }
    loads[best] += option.batch.estimate
    makespan = makespan.max(loads[best])
    worker_of.push(best)
  }
  { options, worker_of, loads, makespan, }
}

///|
fn exchange(schedule : Schedule, busiest : Int32, other_max : Int32) -> Bool {
  let loads = schedule.loads
  let worker_of = schedule.worker_of
  let options = schedule.options
  let busiest_bit = 1U << busiest
  let departures : Array[Int32] = []
  let arrivals : Array[Int32] = []
  for i, option in options {
    if worker_of[i] == busiest {
      if option.eligible.length() > 1 {
        departures.push(i)
      }
    } else if (option.mask & busiest_bit) != 0U {
      arrivals.push(i)
    }
  }
  // Limit the search in large manifests while retaining deterministic order.
  let pair_budget = 2048
  let mut evaluated = 0
  let mut best = schedule.makespan
  let mut swap : (Int32, Int32, Int32)? = None
  for i in departures {
    if evaluated == pair_budget {
      break
    }
    let outgoing = options[i]
    for j in arrivals {
      if evaluated == pair_budget {
        break
      }
      evaluated += 1
      let destination = worker_of[j]
      let delta = outgoing.batch.estimate - options[j].batch.estimate
      if delta <= 0 || (outgoing.mask & (1U << destination)) == 0U {
        continue
      }
      // The destination's load increases, so other_max remains a valid
      // baseline even when that load is the old second-largest one.
      let candidate = other_max
        .max(loads[busiest] - delta)
        .max(loads[destination] + delta)
      if candidate < best {
        best = candidate
        swap = Some((i, j, delta))
      }
    }
  }
  guard swap is Some((i, j, delta)) else { return false }
  let destination = worker_of[j]
  loads[busiest] -= delta
  loads[destination] += delta
  worker_of[i] = destination
  worker_of[j] = busiest
  schedule.makespan = best
  true
}

///|
fn improve(schedule : Schedule, lower_bound : Int32) -> Unit {
  let loads = schedule.loads
  // Each pass tries a move first, then a bounded exchange if moves stall.
  for _ in 0..<16 {
    if schedule.makespan <= lower_bound {
      break
    }
    let mut busiest = 0
    let mut other_max = 0
    for i in 1.. loads[busiest] {
        other_max = loads[busiest]
        busiest = i
      } else {
        other_max = other_max.max(loads[i])
      }
    }
    // A move or exchange cannot strictly lower tied maximum loads.
    if other_max == schedule.makespan {
      break
    }
    let mut best = schedule.makespan
    let mut relocation : (Int32, Int32)? = None
    for i, option in schedule.options {
      if schedule.worker_of[i] != busiest {
        continue
      }
      let estimate = option.batch.estimate
      let baseline = other_max.max(loads[busiest] - estimate)
      for destination in option.eligible {
        if destination == busiest {
          continue
        }
        let candidate = baseline.max(loads[destination] + estimate)
        if candidate < best {
          best = candidate
          relocation = Some((i, destination))
        }
      }
    }
    guard relocation is Some((i, destination)) else {
      if exchange(schedule, busiest, other_max) {
        continue
      }
      break
    }
    let estimate = schedule.options[i].batch.estimate
    loads[busiest] -= estimate
    loads[destination] += estimate
    schedule.worker_of[i] = destination
    schedule.makespan = best
  }
}

///|
fn make_shards(schedule : Schedule, workers : Array[Worker]) -> Array[Shard] {
  let assignments : Array[Array[String]] = Array::makei(workers.length(), _ => {
    []
  })
  for i, option in schedule.options {
    let jobs = assignments[schedule.worker_of[i]]
    for job in option.batch.jobs {
      jobs.push(job.id)
    }
  }
  workers.mapi((i, worker) => {
    worker: worker.id,
    jobs: assignments[i],
    estimated_ms: schedule.loads[i],
  })
}

///|
/// Select a deterministic initial assignment and improve it with whole-group moves and exchanges.
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, workers.length()))
  let first = assign(options, workers.length())
  let schedule = if first.makespan > lower &&
    options.length() > 1 &&
    options[0].eligible.length() !=
    options[options.length() - 1].eligible.length() {
    let duration_first = options.copy()
    duration_first.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(duration_first, workers.length())
    if alternative.makespan < first.makespan {
      alternative
    } else {
      first
    }
  } else {
    first
  }
  improve(schedule, lower)
  let makespan = schedule.makespan
  {
    shards: make_shards(schedule, workers),
    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),
  }
}