///|
/// A physical operation, applied in list order before the named job.
pub(all) struct Action {
  kind : String
  feeder : String
  slot : Int32
}

///|
pub(all) struct Step {
  job : String
  positions : Array[Int32]
  actions : Array[Action]
  cost : Int32
}

///|
pub(all) struct Plan {
  steps : Array[Step]
  cost : Int32
}

///|
pub extend Action with ToJson::{to_json}

///|
pub extend Action with @json.FromJson::{from_json}

///|
pub extend Step with ToJson::{to_json}

///|
pub extend Step with @json.FromJson::{from_json}

///|
pub extend Plan with ToJson::{to_json}

///|
pub extend Plan with @json.FromJson::{from_json}

///|
/// Keeping an idle unit never increases the optimum. Its removal can wait
/// until the first conflict, with no change to the price of removal.
fn retain(
  s : Shift,
  prev : Array[Int32],
  pattern : Array[Int32],
) -> Array[Int32] {
  let next = pattern.copy()
  let occupied = Array::make(s.slots + 1, false)
  for i, p in pattern {
    if p > 0 {
      for k in p..<(p + s.feeders[i].width) {
        occupied[k] = true
      }
    }
  }
  for i, p in prev {
    if p == 0 || next[i] != 0 {
      continue
    }
    let mut ok = true
    for k in p..<(p + s.feeders[i].width) {
      if occupied[k] {
        ok = false
        break
      }
    }
    if ok {
      next[i] = p
    }
  }
  next
}

///|
fn price(s : Shift, a : Array[Int32], b : Array[Int32]) -> Int32 {
  let mut n = 0
  for i, f in s.feeders {
    if a[i] != b[i] {
      if a[i] > 0 {
        n += f.unload
      }
      if b[i] > 0 {
        n += f.load
      }
    }
  }
  n
}

///|
fn change(s : Shift, j : Job, a : Array[Int32], b : Array[Int32]) -> Step {
  let actions : Array[Action] = []
  for i, f in s.feeders {
    if a[i] != b[i] && a[i] > 0 {
      actions.push({ kind: "unload", feeder: f.id, slot: a[i], })
    }
  }
  for i, f in s.feeders {
    if a[i] != b[i] && b[i] > 0 {
      actions.push({ kind: "load", feeder: f.id, slot: b[i], })
    }
  }
  { job: j.id, positions: b, actions, cost: price(s, a, b), }
}

///|
/// Minimize immediate cost only. First enumerated placement breaks ties.
pub fn greedy(s : Shift) -> Plan raise InputError {
  validate(s)
  let mut prev = s.initial
  let steps = []
  let mut cost = 0
  for i, j in s.jobs {
    let candidates = arrangements(s, i)
    if candidates.is_empty() {
      raise Invalid(j.id + " has no arrangement")
    }
    let mut best = retain(s, prev, candidates[0])
    let mut low = price(s, prev, best)
    for row in candidates {
      let b = retain(s, prev, row)
      let n = price(s, prev, b)
      if n < low {
        best = b
        low = n
      }
    }
    steps.push(change(s, j, prev, best))
    cost += low
    prev = best
  }
  { steps, cost, }
}