///|
/// A conflict is a jointly infeasible subset of a job's requirements, with
/// all rack restrictions and locked units retained. Minimal means removing
/// any one named requirement makes that subset feasible.
pub(all) struct Diagnosis {
  status : String
  job : String
  conflict : Array[String]
  minimal : Bool
  probes : Int32
}

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

///|
/// Diagnose one job without considering transition costs.
pub fn diagnose(
  s : Shift,
  index : Int32,
  budget~ : Int32 = 500000,
) -> Diagnosis raise InputError {
  validate(s)
  if index < 0 || index >= s.jobs.length() {
    raise Invalid("job index out of range")
  }
  if budget < 1 || budget > 2000000 {
    raise Invalid("budget outside 1..2000000")
  }
  let job = s.jobs[index]
  let first = patterns(s, job, budget, first_only=true)
  let mut probes = first.probes
  if first.limited {
    return {
      status: "limit",
      job: job.id,
      conflict: [],
      minimal: false,
      probes,
    }
  }
  if !first.rows.is_empty() {
    return {
      status: "feasible",
      job: job.id,
      conflict: [],
      minimal: false,
      probes,
    }
  }
  let mut conflict = job.need.copy()
  let mut cursor = 0
  while cursor < conflict.length() {
    let trial = []
    for i, id in conflict {
      if i != cursor {
        trial.push(id)
      }
    }
    let result = patterns(
      s,
      { ..job, need: trial, },
      budget - probes,
      first_only=true,
    )
    probes += result.probes
    if result.limited {
      return {
        status: "infeasible",
        job: job.id,
        conflict,
        minimal: false,
        probes,
      }
    }
    if result.rows.is_empty() {
      conflict = trial
    } else {
      cursor += 1
    }
  }
  { status: "infeasible", job: job.id, conflict, minimal: true, probes, }
}