///|
/// A pure operand read by a Plan VM statement.
/// Read-only externally; only `pkgs/rego/compile` constructs validated operands.
#derive(Eq, Debug)
pub enum Operand {
  /// Pre-evaluated ground constant value.
  Const(@value.Value)
  /// Local slot index in the current VM frame.
  Local(Int32)
  /// The `input` root document (subject to active `with` overlays).
  Input
  /// The `data` root document (subject to active `with` overlays).
  Data
}

///|
/// A structural unification pattern (`lhs = rhs` or function parameter pattern).
#derive(Eq, Debug)
pub enum Pattern {
  /// Constant ground value.
  PConst(@value.Value)
  /// Local slot (bound or unbound).
  PLocal(Int32)
  /// Anonymous wildcard (`_`) matching any defined value.
  PWildcard
  /// Array pattern matching an array of equal length element-wise.
  PArray(ReadOnlyArray[Pattern])
  /// Object pattern matching an object with identical keys and values.
  PObject(ReadOnlyArray[(Pattern, Pattern)])
  /// Set pattern matching a set of equal elements.
  PSet(ReadOnlyArray[Pattern])
}

///|
/// One segment of a runtime reference lookup `base[seg0][seg1]...`.
#derive(Eq, Debug)
pub enum RefKey {
  /// Static string key (from `.ident` or `["str"]`).
  Static(String)
  /// Already-grounded operand key (`[expr]` or `[bound_var]`).
  Dynamic(Operand)
  /// Unbound local slot key (`[unbound_var]` or `[_]`) that scans all keys.
  BindKey(Int32)
  /// Composite key pattern (`[[1, x]]` or `[{"k": x}]`) that scans all keys
  /// and unifies each key against the pattern.
  BindPattern(Pattern)
}

///|
/// Target of a `with  as ` overlay.
#derive(Eq, Debug)
pub enum WithTarget {
  /// Overrides `input` or a path under `input` (empty path replaces whole `input`).
  WithInput(ReadOnlyArray[String])
  /// Overrides a path under `data` (static data, virtual rule, or function).
  WithData(ReadOnlyArray[String])
  /// Overrides a registered built-in function name.
  WithBuiltin(@builtins.BuiltinName)
}

///|
/// Replacement supplied by a `with  as ` overlay.
#derive(Eq, Debug)
pub enum WithValue {
  /// Replaces the target with a runtime value operand.
  WithOperand(Operand)
  /// Replaces a callable target with a user-defined Rego function path.
  WithFuncPath(ReadOnlyArray[String])
  /// Replaces a callable target with another registered built-in.
  WithBuiltinName(@builtins.BuiltinName)
}

///|
/// One resolved `with` modifier overlay.
#derive(Eq, Debug)
pub struct WithOverlay {
  target : WithTarget
  value : WithValue
}

///|
/// One part of a compiled Rego template string (`$"..."` or `` $`...` ``).
#derive(Eq, Debug)
pub enum CompiledTemplatePart {
  /// Literal text segment.
  Lit(String)
  /// Interpolated expression evaluated in a mini-block yielding `slot`.
  /// If evaluation yields zero solutions, the VM formats `""`.
  Interp(stmts~ : ReadOnlyArray[Stmt], slot~ : Int32)
}

///|
/// A compiled branch inside an `else` chain.
#derive(Eq, Debug)
pub struct CompiledBranch {
  num_slots : Int32
  body : ReadOnlyArray[Stmt]
  result : Operand
}

///|
/// A structured Plan VM instruction.
#derive(Eq, Debug)
pub enum Stmt {
  /// Structured nested block; `Break(depth)` exits `depth + 1` enclosing blocks.
  Block(ReadOnlyArray[Stmt])
  /// Breaks out of `depth` enclosing `Block` statements (0 = innermost).
  Break(Int32)
  /// Succeeds if `operand` is bound and not `Bool(false)`.
  AssertTruthy(Operand)
  /// Succeeds if `operand` is bound and is an `Array`, `Object`, or `Set`.
  AssertCollection(Operand)
  /// Assigns `dst := src` (fails if `src` is unbound).
  Assign(dst~ : Int32, src~ : Operand)
  /// Checks `lhs == rhs` (fails if either is unbound or unequal).
  Equal(lhs~ : Operand, rhs~ : Operand)
  /// Structural Rego unification `lhs = rhs` with trail-based backtracking.
  Unify(lhs~ : Pattern, rhs~ : Pattern)
  /// Evaluates `base[segments...]` into `dst`. Any `BindKey(slot)` segment
  /// introduces a backtracking choice point scanning keys/elements.
  EvalRef(dst~ : Int32, base~ : Operand, segments~ : ReadOnlyArray[RefKey])
  /// Backtracking scan over `domain` (`Array`, `Object`, or `Set`), binding
  /// `key_slot` (if present) and `val_slot` for each element.
  Scan(domain~ : Operand, key_slot~ : Int32?, val_slot~ : Int32)
  /// Backtracking scan for `walk(target, out_pattern)`.
  WalkScan(target~ : Operand, out~ : Pattern)
  /// Negation-as-failure: succeeds iff `body` produces zero solutions.
  Not(ReadOnlyArray[Stmt])
  /// Invokes a built-in (respecting active `with` overrides).
  /// Fails if the built-in returns `None` (undefined).
  /// If `dst` is `Some(slot)`, binds result into `slot`.
  CallBuiltin(
    name~ : @builtins.BuiltinName,
    args~ : ReadOnlyArray[Operand],
    dst~ : Int32?,
  )
  /// Evaluates a virtual rule document at `path` under `data`, respecting `with`
  /// overrides and memoization. Fails if undefined.
  CallRule(path~ : ReadOnlyArray[String], dst~ : Int32)
  /// Evaluates a user-defined function at `path` with `args`, respecting `with`
  /// overrides. Fails if undefined.
  CallFunc(
    path~ : ReadOnlyArray[String],
    args~ : ReadOnlyArray[Operand],
    dst~ : Int32,
  )
  /// Executes `body` under scoped `with` overlays.
  With(overlays~ : ReadOnlyArray[WithOverlay], body~ : ReadOnlyArray[Stmt])
  /// Evaluates an `else` chain in order, binding the first succeeding branch's
  /// result into `dst`.
  ElseChain(branches~ : ReadOnlyArray[CompiledBranch], dst~ : Int32)
  /// Initializes `dst` to an empty array.
  MakeArray(dst~ : Int32)
  /// Appends `elem` to the array currently stored in `arr`.
  ArrayPush(arr~ : Int32, elem~ : Operand)
  /// Initializes `dst` to an empty set.
  MakeSet(dst~ : Int32)
  /// Inserts `elem` into the set currently stored in `set`.
  SetAdd(set~ : Int32, elem~ : Operand)
  /// Initializes `dst` to an empty object.
  MakeObject(dst~ : Int32)
  /// Inserts `(key, val)` into the object currently stored in `obj`.
  ObjectInsert(obj~ : Int32, key~ : Operand, val~ : Operand)
  /// Evaluates an array comprehension `[elem | body]` into `dst`.
  BuildArrayComp(dst~ : Int32, elem~ : Operand, body~ : ReadOnlyArray[Stmt])
  /// Evaluates a set comprehension `{elem | body}` into `dst`.
  BuildSetComp(dst~ : Int32, elem~ : Operand, body~ : ReadOnlyArray[Stmt])
  /// Evaluates an object comprehension `{key: val | body}` into `dst`.
  BuildObjectComp(
    dst~ : Int32,
    key~ : Operand,
    val~ : Operand,
    body~ : ReadOnlyArray[Stmt],
  )
  /// Evaluates a template string into `dst`.
  FormatTemplate(dst~ : Int32, parts~ : ReadOnlyArray[CompiledTemplatePart])
  /// Emits one solution row of output variable bindings into the query result set.
  ResultSetAdd(bindings~ : ReadOnlyArray[(String, Int32)])
}

///|
/// Leaf contribution mode for dynamic ref-head object clauses (`a.b[c].d := v`
/// or `a.b[c].d contains v`).
#derive(Eq, Debug)
pub enum DynamicLeafKind {
  /// Assigns a complete value at the dynamic key path (conflict if unequal).
  DynamicValue
  /// Inserts a member into a partial set at the dynamic key path.
  DynamicSetElem
}

///|
/// A compiled clause for a complete rule, partial set, partial object, dynamic
/// ref-head rule, or user-defined function.
#derive(Eq, Debug)
pub struct CompiledClause {
  num_slots : Int32
  param_patterns : ReadOnlyArray[Pattern]
  key_operands : ReadOnlyArray[Operand]
  leaf_kind : DynamicLeafKind
  value_operand : Operand
  body : ReadOnlyArray[Stmt]
  else_branches : ReadOnlyArray[CompiledBranch]
  rule_metadata : @value.Value?
  chain_metadata : @value.Value?
}

///|
/// A node in the compiled `data.*` virtual document tree.
#derive(Eq, Debug)
pub enum CompiledRuleNode {
  /// Pure package / namespace container with child nodes.
  Package(children~ : ReadOnlyArray[(String, CompiledRuleNode)])
  /// Complete rule producing a single value (with optional ground or
  /// comprehension default).
  Complete(
    clauses~ : ReadOnlyArray[CompiledClause],
    default_value~ : @value.Value?,
    default_branch~ : CompiledBranch?,
  )
  /// Partial set rule producing a `RegoSet` (empty set when no clause matches).
  PartialSet(clauses~ : ReadOnlyArray[CompiledClause])
  /// Virtual object rule combining static child rules and dynamic `[k] := v` /
  /// general ref-head clauses.
  VirtualObject(
    static_children~ : ReadOnlyArray[(String, CompiledRuleNode)],
    dynamic_clauses~ : ReadOnlyArray[CompiledClause],
  )
  /// User-defined function (not materialized when traversing `data.*` documents).
  Function(
    arity~ : Int32,
    clauses~ : ReadOnlyArray[CompiledClause],
    default_value~ : @value.Value?,
  )
}

///|
/// An immutable compiled Rego v1 policy ready for VM execution.
struct CompiledPolicy {
  root : CompiledRuleNode
  builtins : @builtins.BuiltinRegistry
  rule_paths : ReadOnlyArray[ReadOnlyArray[String]]
}

///|
/// Returns the compiled virtual document tree rooted at `data`.
pub fn CompiledPolicy::root(self : CompiledPolicy) -> CompiledRuleNode {
  self.root
}

///|
/// Returns the immutable built-in registry bound to this compiled policy.
pub fn CompiledPolicy::builtins(
  self : CompiledPolicy,
) -> @builtins.BuiltinRegistry {
  self.builtins
}

///|
/// Returns all compiled rule and function paths under `data`.
pub fn CompiledPolicy::rule_paths(
  self : CompiledPolicy,
) -> ReadOnlyArray[ReadOnlyArray[String]] {
  self.rule_paths
}

///|
/// Looks up a compiled rule or package node by path segments under `data`.
pub fn CompiledPolicy::lookup_node(
  self : CompiledPolicy,
  path : ArrayView[String],
) -> CompiledRuleNode? {
  let mut cur = self.root
  for seg in path {
    let children : ReadOnlyArray[(String, CompiledRuleNode)] = match cur {
      Package(children~) => children
      VirtualObject(static_children~, ..) => static_children
      _ => return None
    }
    let mut found : CompiledRuleNode? = None
    for entry in children {
      if entry.0 == seg {
        found = Some(entry.1)
        break
      }
    }
    match found {
      Some(next) => cur = next
      None => return None
    }
  }
  Some(cur)
}

///|
/// An immutable compiled Rego v1 query ready for VM execution.
#derive(Eq, Debug)
struct CompiledQuery {
  num_slots : Int32
  body : ReadOnlyArray[Stmt]
  output_bindings : ReadOnlyArray[(String, Int32)]
  expr_slots : ReadOnlyArray[Int32]
}

///|
/// Number of local variable slots required by this query frame.
pub fn CompiledQuery::num_slots(self : CompiledQuery) -> Int32 {
  self.num_slots
}

///|
/// Top-level scheduled Plan VM statements for this query.
pub fn CompiledQuery::body(self : CompiledQuery) -> ReadOnlyArray[Stmt] {
  self.body
}

///|
/// User-visible variable bindings `(name, slot)` recorded per solution.
pub fn CompiledQuery::output_bindings(
  self : CompiledQuery,
) -> ReadOnlyArray[(String, Int32)] {
  self.output_bindings
}

///|
/// Result value slots for each top-level expression in the query.
pub fn CompiledQuery::expr_slots(self : CompiledQuery) -> ReadOnlyArray[Int32] {
  self.expr_slots
}