///|
/// Each layer stores the cheapest history for each complete physical rack.
priv struct Node {
  pos : Array[Int32]
  mut total : Int32
  mut parent : Int32
}

///|
/// Only successful results include a plan. At limit or infeasible, job names
/// the layer where search stopped.
pub(all) struct Outcome {
  status : String
  job : String
  probes : Int32
  edges : Int32
  states : Int32
  plan : Plan?
}

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

///|
/// Minimize total action weight for a fixed job sequence, with no terminal teardown.
pub fn solve(s : Shift, budget~ : Int32 = 500000) -> Outcome raise InputError {
  validate(s)
  if budget < 1 || budget > 2000000 {
    raise Invalid("budget outside 1..2000000")
  }
  let root : Node = { pos: s.initial, total: 0, parent: -1, }
  let layers = [[root]]
  let mut probes = 0
  let mut edges = 0
  let mut states = 1
  fn stop(status : String, job : String) -> Outcome {
    { status, job, probes, edges, states, plan: None, }
  }
  for t, j in s.jobs {
    let c = patterns(s, j, budget - probes - edges)
    probes += c.probes
    if c.limited {
      return stop("limit", j.id)
    }
    if c.rows.is_empty() {
      return stop("infeasible", j.id)
    }
    let layer : Array[Node] = []
    let index : Map[String, Int32] = Map([])
    for k, prev in layers[t] {
      for row in c.rows {
        if probes + edges >= budget {
          return stop("limit", j.id)
        }
        edges += 1
        let pos = retain(s, prev.pos, row)
        let total = prev.total + price(s, prev.pos, pos)
        let key = Json(pos).stringify()
        match index.get(key) {
          None => {
            if states >= 50000 {
              return stop("limit", j.id)
            }
            index[key] = layer.length()
            layer.push({ pos, total, parent: k, })
            states += 1
          }
          Some(i) =>
            if total < layer[i].total {
              layer[i].total = total
              layer[i].parent = k
            }
        }
      }
    }
    layers.push(layer)
  }
  let last = layers[s.jobs.length()]
  let mut ix = 0
  for i, n in last {
    if n.total < last[ix].total {
      ix = i
    }
  }
  let cost = last[ix].total
  let steps = []
  for t = s.jobs.length(); t > 0; t = t - 1 {
    let n = layers[t][ix]
    ix = n.parent
    steps.push(change(s, s.jobs[t - 1], layers[t - 1][ix].pos, n.pos))
  }
  steps.rev_in_place()
  {
    status: "optimal",
    job: "",
    probes,
    edges,
    states,
    plan: Some({ steps, cost, }),
  }
}