///|
/// Validate the complete graph before any checks run; selection includes prerequisites.
pub fn Registry::plan(
  self : Registry,
  selected~ : Array[String] = [],
) -> Array[Rule] raise DoctorError {
  let pending = self.list().filter(r => r.enabled)
  for r in pending {
    for dep in r.dependencies {
      match self.get(dep) {
        None => raise DoctorError("unknown prerequisite: \{dep}")
        Some(rule) =>
          if !rule.enabled {
            raise DoctorError("disabled prerequisite: \{dep}")
          }
      }
    }
  }
  let ordered : Array[Rule] = []
  let done : Map[String, Bool] = Map([])
  while pending.length() > 0 {
    let mut best : Int32? = None
    for i, r in pending {
      if r.dependencies.iter().all(d => done.get(d).unwrap_or(false)) {
        match best {
          None => best = Some(i)
          Some(j) =>
            if r.priority < pending[j].priority ||
              (r.priority == pending[j].priority && r.id < pending[j].id) {
              best = Some(i)
            }
        }
      }
    }
    match best {
      None => raise DoctorError("dependency cycle detected")
      Some(i) => {
        let r = pending[i]
        pending.remove(i) |> ignore
        ordered.push(r)
        done[r.id] = true
      }
    }
  }
  if selected.is_empty() {
    return ordered
  }
  let wanted : Map[String, Bool] = Map([])
  for id in selected {
    if !done.contains(id) {
      raise DoctorError("unknown or disabled selection: \{id}")
    }
    wanted[id] = true
  }
  for i = ordered.length() - 1; i >= 0; i = i - 1 {
    let r = ordered[i]
    if wanted.contains(r.id) {
      for dep in r.dependencies {
        wanted[dep] = true
      }
    }
  }
  ordered.filter(r => wanted.contains(r.id))
}

///|
pub struct Cancellation {
  priv mut cancelled : Bool
  priv changed : @cond_var.Cond
}

///|
pub fn Cancellation::new() -> Cancellation {
  { cancelled: false, changed: @cond_var.Cond(), }
}

///|
pub fn Cancellation::cancel(self : Cancellation) -> Unit {
  self.cancelled = true
  self.changed.broadcast()
}

///|
/// Run ready checks in bounded batches and return results in plan order.
/// Async callbacks must yield: CPU-bound infinite callbacks cannot be preempted.
pub async fn Registry::run(
  self : Registry,
  ctx : Context,
  selected~ : Array[String] = [],
  cancellation~ : Cancellation = Cancellation::new(),
  budget_ms~ : Int32 = 120000,
  jobs~ : Int32 = 1,
) -> Array[DiagnosticResult] {
  if budget_ms < 1 || budget_ms > 3600000 {
    raise DoctorError("invalid run budget")
  }
  if jobs < 1 || jobs > 32 {
    raise DoctorError("invalid concurrency limit")
  }
  let plan = self.plan(selected~)
  let start = @async.now()
  let outcomes : Map[String, DiagnosticResult] = Map([])
  while outcomes.length() < plan.length() {
    let work : Array[async () -> DiagnosticResult] = []
    for r in plan {
      if outcomes.contains(r.id) ||
        !r.dependencies.iter().all(id => outcomes.contains(id)) {
        continue
      }
      let blocked = r.dependencies
        .iter()
        .any(id => {
          match outcomes[id].finding.status {
            Passed | Warning => false
            _ => true
          }
        })
      work.push(() => {
        execute_rule(
          r,
          ctx,
          cancellation,
          blocked,
          budget_ms.to_int64() - (@async.now() - start),
        )
      })
      if work.length() == jobs {
        break
      }
    }
    for result in @async.all(work) {
      outcomes[result.rule_id] = result
    }
  }
  plan.map(r => outcomes[r.id])
}

///|
async fn execute_rule(
  r : Rule,
  ctx : Context,
  cancellation : Cancellation,
  blocked : Bool,
  remaining : Int64,
) -> DiagnosticResult {
  let began = @async.now()
  let result = if cancellation.cancelled {
    finding(Skipped, "cancelled", "Run was cancelled")
  } else if remaining <= 0L {
    finding(Skipped, "budget_exhausted", "Run budget exhausted")
  } else if blocked {
    finding(Skipped, "dependency_blocked", "A prerequisite did not pass")
  } else {
    let timeout = if remaining < r.timeout_ms.to_int64() {
      remaining.to_int()
    } else {
      r.timeout_ms
    }
    try {
      match
        @async.with_timeout_opt(timeout, () => {
          @async.any([
            () => {
              while !cancellation.cancelled {
                cancellation.changed.wait()
              }
              finding(Skipped, "cancelled", "Run was cancelled")
            },
            () => (r.execute)({ ..ctx, facts: ctx.facts.copy(), }),
          ])
        }) {
        Some(value) => value
        None =>
          finding(
            Error,
            "timeout",
            "Rule exceeded its deadline",
            remediation="Check the target and retry with a bounded timeout",
          )
      }
    } catch {
      err => {
        if @async.is_being_cancelled() {
          raise err
        }
        finding(
          Error,
          "execution_error",
          "Rule execution raised an error",
          remediation="Check platform capabilities and target access",
        )
      }
    }
  }
  {
    rule_id: r.id,
    category: r.category,
    severity: r.severity,
    finding: result,
    duration_ms: @async.now() - began,
  }
}