///|
/// Conditions inspect caller-provided facts, never execute commands.
pub(all) enum Condition {
  Always
  Present(String)
  Equals(String, String)
  All(Array[Condition])
  Any(Array[Condition])
  Not(Condition)
}

///|
pub fn Condition::evaluate(
  self : Condition,
  facts : Map[String, String],
  max_depth~ : Int32 = 16,
  max_nodes~ : Int32 = 1024,
) -> Bool raise DoctorError {
  if max_depth < 1 || max_depth > 64 || max_nodes < 1 || max_nodes > 10000 {
    raise DoctorError("invalid condition limits")
  }
  let remaining = Ref(max_nodes)
  fn visit(node : Condition, depth : Int32) -> Bool raise DoctorError {
    remaining.val -= 1
    if depth > max_depth || remaining.val < 0 {
      raise DoctorError("condition complexity exceeded")
    }
    match node {
      Always => true
      Present(key) => facts.get(key) is Some(value) && value.trim().length() > 0
      Equals(key, value) => facts.get(key) == Some(value)
      All(children) => {
        let mut value = true
        for child in children {
          let result = visit(child, depth + 1)
          value = value && result
        }
        value
      }
      Any(children) => {
        let mut value = false
        for child in children {
          let result = visit(child, depth + 1)
          value = value || result
        }
        value
      }
      Not(child) => !visit(child, depth + 1)
    }
  }
  visit(self, 1)
}

///|
pub fn conditional(value : Rule, condition : Condition) -> Rule {
  {
    ..value,
    execute: ctx => {
      if condition.evaluate(ctx.facts) {
        (value.execute)(ctx)
      } else {
        finding(Skipped, "condition_false", "Rule condition did not match")
      }
    },
  }
}