///|
/// Raised when constructing engine configuration values breaks a domain rule.
#derive(Eq, Debug)
pub(all) suberror EngineError {
  /// Step budget limit was zero or negative.
  InvalidBudget(limit~ : Int32)
}

///|
pub impl Show for EngineError with fn output(self, logger) {
  match self {
    InvalidBudget(limit~) =>
      logger.write_string("step budget must be positive, got \{limit}")
  }
}

///|
/// Raised when Plan VM evaluation fails with a runtime error.
#derive(Eq, Debug)
pub(all) suberror EvalError {
  /// Execution reached the configured `StepBudget` limit.
  BudgetExceeded(limit~ : Int32)
  /// Complete rule, partial object key, or object comprehension produced
  /// conflicting values.
  Conflict(path~ : String, message~ : String)
  /// A built-in raised an error while strict built-in errors were enabled.
  BuiltinFailure(name~ : String, message~ : String)
}

///|
pub impl Show for EvalError with fn output(self, logger) {
  match self {
    BudgetExceeded(limit~) =>
      logger.write_string("evaluation exceeded step budget of \{limit}")
    Conflict(path~, message~) =>
      logger.write_string("eval conflict at `\{path}`: \{message}")
    BuiltinFailure(name~, message~) =>
      logger.write_string("built-in `\{name}` failed: \{message}")
  }
}

///|
/// A validated positive deterministic instruction step limit for the Plan VM.
#derive(Eq, Compare, Hash, Debug)
struct StepBudget {
  limit : Int32
}

///|
/// Constructs a validated `StepBudget`, rejecting non-positive limits.
pub fn StepBudget::StepBudget(limit : Int32) -> StepBudget raise EngineError {
  if limit <= 0 {
    raise InvalidBudget(limit~)
  }
  { limit, }
}

///|
/// Returns the default `StepBudget` (100,000 VM steps).
pub fn StepBudget::default() -> StepBudget {
  { limit: 100_000, }
}

///|
/// Returns the maximum number of VM steps permitted by this budget.
pub fn StepBudget::limit(self : StepBudget) -> Int32 {
  self.limit
}

///|
/// Immutable options controlling Plan VM evaluation.
struct EngineOptions {
  step_budget : StepBudget
  builtins : @builtins.BuiltinRegistry
  strict_builtin_errors : Bool
  clock : @builtins.Clock
  random_seed : @builtins.RandomSeed
}

///|
/// Returns default engine options (`StepBudget::default()`, standard Tier-1 +
/// Tier-2 pure built-ins, epoch `Clock`, default deterministic `RandomSeed`,
/// and standard OPA soft-undefined built-in error behavior).
pub fn EngineOptions::default() -> EngineOptions {
  {
    step_budget: StepBudget::default(),
    builtins: @builtins.BuiltinRegistry::standard(),
    strict_builtin_errors: false,
    clock: @builtins.Clock::epoch(),
    random_seed: @builtins.RandomSeed::default(),
  }
}

///|
/// Returns a copy of these options with a different `StepBudget`.
pub fn EngineOptions::with_step_budget(
  self : EngineOptions,
  step_budget : StepBudget,
) -> EngineOptions {
  { ..self, step_budget, }
}

///|
/// Returns a copy of these options with a custom `BuiltinRegistry`.
pub fn EngineOptions::with_builtins(
  self : EngineOptions,
  builtins : @builtins.BuiltinRegistry,
) -> EngineOptions {
  { ..self, builtins, }
}

///|
/// Returns a copy of these options with `strict_builtin_errors` toggled.
pub fn EngineOptions::with_strict_builtin_errors(
  self : EngineOptions,
  strict : Bool,
) -> EngineOptions {
  { ..self, strict_builtin_errors: strict, }
}

///|
/// Returns a copy of these options with an explicit injected `Clock`.
pub fn EngineOptions::with_clock(
  self : EngineOptions,
  clock : @builtins.Clock,
) -> EngineOptions {
  { ..self, clock, }
}

///|
/// Returns a copy of these options with an explicit injected `RandomSeed`.
pub fn EngineOptions::with_random_seed(
  self : EngineOptions,
  random_seed : @builtins.RandomSeed,
) -> EngineOptions {
  { ..self, random_seed, }
}

///|
/// Returns the configured step budget.
pub fn EngineOptions::step_budget(self : EngineOptions) -> StepBudget {
  self.step_budget
}

///|
/// Returns the configured built-in registry.
pub fn EngineOptions::builtins(
  self : EngineOptions,
) -> @builtins.BuiltinRegistry {
  self.builtins
}

///|
/// Reports whether built-in errors abort evaluation instead of returning undefined.
pub fn EngineOptions::strict_builtin_errors(self : EngineOptions) -> Bool {
  self.strict_builtin_errors
}

///|
/// Returns the configured deterministic `Clock`.
pub fn EngineOptions::clock(self : EngineOptions) -> @builtins.Clock {
  self.clock
}

///|
/// Returns the configured deterministic `RandomSeed`.
pub fn EngineOptions::random_seed(self : EngineOptions) -> @builtins.RandomSeed {
  self.random_seed
}

///|
/// One immutable solution row returned by evaluating a Rego v1 query.
#derive(Eq, Debug)
struct BindingSet {
  bindings : ReadOnlyArray[(String, @value.Value)]
  expressions : ReadOnlyArray[@value.Value]
}

///|
/// Returns all variable bindings `(name, value)` in this solution row.
pub fn BindingSet::bindings(
  self : BindingSet,
) -> ReadOnlyArray[(String, @value.Value)] {
  self.bindings
}

///|
/// Looks up a variable binding by name in this solution row.
pub fn BindingSet::get(self : BindingSet, name : String) -> @value.Value? {
  for pair in self.bindings {
    if pair.0 == name {
      return Some(pair.1)
    }
  }
  None
}

///|
/// Returns all top-level expression values in this solution row.
pub fn BindingSet::expressions(
  self : BindingSet,
) -> ReadOnlyArray[@value.Value] {
  self.expressions
}

///|
/// Returns the value of the first top-level expression, if any.
pub fn BindingSet::value(self : BindingSet) -> @value.Value? {
  if self.expressions.is_empty() {
    None
  } else {
    Some(self.expressions[0])
  }
}

///|
/// Immutable result set produced by evaluating a Rego v1 query on the Plan VM.
#derive(Eq, Debug)
struct EvalResult {
  rows : ReadOnlyArray[BindingSet]
}

///|
/// Returns all solution rows produced by the query.
pub fn EvalResult::rows(self : EvalResult) -> ReadOnlyArray[BindingSet] {
  self.rows
}

///|
/// Reports whether the query produced zero solutions (undefined).
pub fn EvalResult::is_empty(self : EvalResult) -> Bool {
  self.rows.is_empty()
}

///|
/// Reports whether the query produced at least one solution.
pub fn EvalResult::is_defined(self : EvalResult) -> Bool {
  !self.rows.is_empty()
}

///|
/// Number of solution rows produced by the query.
pub fn EvalResult::length(self : EvalResult) -> Int32 {
  self.rows.length()
}

///|
/// Returns the first expression value of the first solution row, if defined.
pub fn EvalResult::first_value(self : EvalResult) -> @value.Value? {
  if self.rows.is_empty() {
    None
  } else {
    self.rows[0].value()
  }
}