///|
/// Raised when constructing or invoking a built-in breaks a contract.
#derive(Eq, Debug)
pub(all) suberror BuiltinError {
  /// Built-in name is empty or contains invalid characters/segments.
  InvalidName(text~ : String)
  /// Arity is negative.
  InvalidArity(arity~ : Int32)
  /// Wrong argument count passed to a built-in.
  WrongArity(name~ : String, expected~ : Int32, actual~ : Int32)
  /// Built-in raised a hard error (for example division by zero in strict mode
  /// or invalid format string).
  EvalFailure(name~ : String, message~ : String)
  /// Built-in work exceeded the remaining VM step budget.
  BudgetExceeded(limit~ : Int32)
}

///|
pub impl Show for BuiltinError with fn output(self, logger) {
  match self {
    InvalidName(text~) => logger.write_string("invalid built-in name `\{text}`")
    InvalidArity(arity~) =>
      logger.write_string("invalid built-in arity \{arity}")
    WrongArity(name~, expected~, actual~) =>
      logger.write_string(
        "built-in `\{name}` expected \{expected} arguments, got \{actual}",
      )
    EvalFailure(name~, message~) =>
      logger.write_string("built-in `\{name}` failed: \{message}")
    BudgetExceeded(limit~) =>
      logger.write_string("built-in exceeded remaining step budget of \{limit}")
  }
}

///|
fn is_valid_builtin_segment(seg : StringView) -> Bool {
  if seg.is_empty() {
    return false
  }
  let c0 = seg.code_unit_at(0).to_int()
  let start_ok = (c0 >= 0x41 && c0 <= 0x5A) ||
    (c0 >= 0x61 && c0 <= 0x7A) ||
    c0 == 0x5F
  if !start_ok {
    return false
  }
  for i in 1..= 0x41 && c <= 0x5A) ||
      (c >= 0x61 && c <= 0x7A) ||
      (c >= 0x30 && c <= 0x39) ||
      c == 0x5F
    if !ok {
      return false
    }
  }
  true
}

///|
/// A validated Rego built-in name (dot-separated identifier segments such as
/// `count`, `object.union_n`, or `custom.double`).
#derive(Eq, Compare, Hash, Debug)
struct BuiltinName {
  text : String
}

///|
/// Constructs a validated built-in name.
pub fn BuiltinName::BuiltinName(
  text : String,
) -> BuiltinName raise BuiltinError {
  if text.is_empty() {
    raise InvalidName(text~)
  }
  for seg in text.split(".") {
    if !is_valid_builtin_segment(seg) {
      raise InvalidName(text~)
    }
  }
  { text, }
}

///|
/// Internal helper for known-valid Tier-1 built-in names.
fn BuiltinName::trusted(text : String) -> BuiltinName {
  { text, }
}

///|
/// Returns the dotted built-in name text.
pub fn BuiltinName::to_string(self : BuiltinName) -> String {
  self.text
}

///|
pub impl Show for BuiltinName with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
/// Argument arity of a Rego built-in function.
/// Private construction guarantees fixed arities are never negative.
#derive(Eq, Hash, Debug)
pub enum BuiltinArity {
  Fixed(Int32)
  Variadic
}

///|
/// Creates a validated non-negative fixed arity.
pub fn BuiltinArity::fixed(n : Int32) -> BuiltinArity raise BuiltinError {
  if n < 0 {
    raise InvalidArity(arity=n)
  }
  Fixed(n)
}

///|
/// Creates a variadic built-in arity.
pub fn BuiltinArity::variadic() -> BuiltinArity {
  Variadic
}

///|
/// Reports whether `count` matches this arity.
pub fn BuiltinArity::accepts(self : BuiltinArity, count : Int32) -> Bool {
  match self {
    Fixed(n) => count == n
    Variadic => true
  }
}

///|
/// Immutable validated signature (name and arity) of a Rego built-in.
#derive(Eq, Hash, Debug)
struct BuiltinSignature {
  name : BuiltinName
  arity : BuiltinArity
}

///|
/// Constructs a built-in signature from a validated name and arity.
pub fn BuiltinSignature::BuiltinSignature(
  name : BuiltinName,
  arity : BuiltinArity,
) -> BuiltinSignature {
  { name, arity, }
}

///|
/// Returns the built-in name in this signature.
pub fn BuiltinSignature::name(self : BuiltinSignature) -> BuiltinName {
  self.name
}

///|
/// Returns the built-in arity in this signature.
pub fn BuiltinSignature::arity(self : BuiltinSignature) -> BuiltinArity {
  self.arity
}

///|
/// Immutable Unix timestamp measured in nanoseconds since the Unix epoch
/// (1970-01-01T00:00:00Z).
#derive(Eq, Compare, Hash, Debug)
struct UnixNanos {
  nanos : Int64
}

///|
/// Constructs a `UnixNanos` value from an exact signed 64-bit nanosecond count.
pub fn UnixNanos::UnixNanos(nanos : Int64) -> UnixNanos {
  { nanos, }
}

///|
/// Returns the Unix epoch (`0` nanoseconds).
pub fn UnixNanos::epoch() -> UnixNanos {
  { nanos: 0L, }
}

///|
/// Returns the signed 64-bit nanosecond count since the Unix epoch.
pub fn UnixNanos::to_int64(self : UnixNanos) -> Int64 {
  self.nanos
}

///|
/// Returns the exact arbitrary-precision nanosecond count since the Unix epoch.
pub fn UnixNanos::to_bigint(self : UnixNanos) -> @bigint.BigInt {
  @bigint.BigInt::from_int64(self.nanos)
}

///|
pub impl Show for UnixNanos with fn output(self, logger) {
  logger.write_string(self.nanos.to_string())
}

///|
/// Immutable injected clock supplying the deterministic timestamp returned by
/// `time.now_ns()` without reading any host wall clock.
#derive(Eq, Compare, Hash, Debug)
struct Clock {
  now : UnixNanos
}

///|
/// Constructs a `Clock` fixed at `now`.
pub fn Clock::Clock(now : UnixNanos) -> Clock {
  { now, }
}

///|
/// Constructs a `Clock` fixed at `nanos` nanoseconds since the Unix epoch.
pub fn Clock::from_unix_nanos(nanos : Int64) -> Clock {
  { now: UnixNanos(nanos), }
}

///|
/// Returns a deterministic `Clock` fixed at the Unix epoch (`0`).
pub fn Clock::epoch() -> Clock {
  { now: UnixNanos::epoch(), }
}

///|
/// Returns the fixed `UnixNanos` timestamp carried by this clock.
pub fn Clock::now(self : Clock) -> UnixNanos {
  self.now
}

///|
/// Returns the fixed timestamp in nanoseconds since the Unix epoch.
pub fn Clock::unix_nanos(self : Clock) -> Int64 {
  self.now.to_int64()
}

///|
/// Immutable injected seed controlling deterministic outputs of `rand.intn`
/// and `uuid.rfc4122` without reading host entropy.
#derive(Eq, Compare, Hash, Debug)
struct RandomSeed {
  seed : UInt64
}

///|
/// Constructs a `RandomSeed` from an explicit 64-bit unsigned seed.
pub fn RandomSeed::RandomSeed(seed : UInt64) -> RandomSeed {
  { seed, }
}

///|
/// Constructs a `RandomSeed` from an explicit 64-bit unsigned seed.
pub fn RandomSeed::from_u64(seed : UInt64) -> RandomSeed {
  { seed, }
}

///|
/// Returns the default deterministic `RandomSeed`.
pub fn RandomSeed::default() -> RandomSeed {
  { seed: 0x9E3779B97F4A7C15UL, }
}

///|
/// Returns the raw 64-bit unsigned seed value.
pub fn RandomSeed::to_u64(self : RandomSeed) -> UInt64 {
  self.seed
}

///|
/// Pure explicit execution context passed into built-in calls (never reads
/// global state, wall clock, host entropy, or I/O).
#derive(Eq, Debug)
struct BuiltinContext {
  rule_metadata : @value.Value?
  chain_metadata : @value.Value?
  clock : Clock
  random_seed : RandomSeed
  remaining_steps : Int32?
}

///|
/// Constructs an empty built-in context with no metadata, epoch clock, and
/// default deterministic random seed.
pub fn BuiltinContext::empty() -> BuiltinContext {
  {
    rule_metadata: None,
    chain_metadata: None,
    clock: Clock::epoch(),
    random_seed: RandomSeed::default(),
    remaining_steps: None,
  }
}

///|
/// Constructs a built-in context carrying pre-computed rule and chain metadata.
pub fn BuiltinContext::with_metadata(
  rule_metadata~ : @value.Value?,
  chain_metadata~ : @value.Value?,
) -> BuiltinContext {
  {
    rule_metadata,
    chain_metadata,
    clock: Clock::epoch(),
    random_seed: RandomSeed::default(),
    remaining_steps: None,
  }
}

///|
/// Returns a copy of this context with an explicit injected `Clock`.
pub fn BuiltinContext::with_clock(
  self : BuiltinContext,
  clock : Clock,
) -> BuiltinContext {
  { ..self, clock, }
}

///|
/// Returns a copy of this context with an explicit injected `RandomSeed`.
pub fn BuiltinContext::with_random_seed(
  self : BuiltinContext,
  random_seed : RandomSeed,
) -> BuiltinContext {
  { ..self, random_seed, }
}

///|
/// Returns a copy of this context carrying the remaining VM step budget for
/// allocation-heavy built-ins such as `numbers.range`.
pub fn BuiltinContext::with_remaining_steps(
  self : BuiltinContext,
  remaining_steps : Int32,
) -> BuiltinContext {
  { ..self, remaining_steps: Some(remaining_steps), }
}

///|
/// Returns the active rule's metadata object, if any.
pub fn BuiltinContext::rule_metadata(self : BuiltinContext) -> @value.Value? {
  self.rule_metadata
}

///|
/// Returns the active metadata chain array, if any.
pub fn BuiltinContext::chain_metadata(self : BuiltinContext) -> @value.Value? {
  self.chain_metadata
}

///|
/// Returns the explicit injected `Clock` for `time.now_ns`.
pub fn BuiltinContext::clock(self : BuiltinContext) -> Clock {
  self.clock
}

///|
/// Returns the explicit injected `RandomSeed` for `rand.intn` and `uuid.rfc4122`.
pub fn BuiltinContext::random_seed(self : BuiltinContext) -> RandomSeed {
  self.random_seed
}

///|
/// Returns the remaining VM step budget available to this built-in call, if set.
pub fn BuiltinContext::remaining_steps(self : BuiltinContext) -> Int32? {
  self.remaining_steps
}

///|
/// Signature and implementation of one pure Rego built-in.
/// Returning `Ok(None)` represents Rego `Undefined` (soft failure).
struct BuiltinEntry {
  name : BuiltinName
  arity : BuiltinArity
  func : (ReadOnlyArray[@value.Value], BuiltinContext) -> Result[
    @value.Value?,
    BuiltinError,
  ]
}

///|
/// Returns the built-in's name.
pub fn BuiltinEntry::name(self : BuiltinEntry) -> BuiltinName {
  self.name
}

///|
/// Returns the built-in's signature.
pub fn BuiltinEntry::signature(self : BuiltinEntry) -> BuiltinSignature {
  { name: self.name, arity: self.arity, }
}

///|
/// Returns the built-in's arity.
pub fn BuiltinEntry::arity(self : BuiltinEntry) -> BuiltinArity {
  self.arity
}

///|
/// Invokes this built-in after checking arity.
pub fn BuiltinEntry::call(
  self : BuiltinEntry,
  args : ArrayView[@value.Value],
  ctx : BuiltinContext,
) -> @value.Value? raise BuiltinError {
  match self.arity {
    Fixed(expected) if args.length() != expected =>
      raise WrongArity(
        name=self.name.to_string(),
        expected~,
        actual=args.length(),
      )
    _ => ()
  }
  match (self.func)(ReadOnlyArray::from_array(args.to_owned()), ctx) {
    Ok(v) => v
    Err(err) => raise err
  }
}

///|
/// Immutable registry mapping `BuiltinName` to pure `BuiltinEntry`.
/// Adding a custom built-in produces a new registry and leaves `self` unchanged.
struct BuiltinRegistry {
  entries : ReadOnlyArray[(String, BuiltinEntry)]
}

///|
/// Constructs an empty registry with no built-ins.
pub fn BuiltinRegistry::empty() -> BuiltinRegistry {
  { entries: ReadOnlyArray::from_array([]), }
}

///|
fn BuiltinRegistry::from_entries(
  raw : Array[(String, BuiltinEntry)],
) -> BuiltinRegistry {
  raw.sort_by((a, b) => a.0.compare(b.0))
  let unique : Array[(String, BuiltinEntry)] = []
  for i in 0.. BuiltinEntry? {
  let key = name.to_string()
  let mut lo = 0
  let mut hi = self.entries.length() - 1
  while lo <= hi {
    let mid = lo + (hi - lo) / 2
    let cmp = self.entries[mid].0.compare(key)
    if cmp == 0 {
      return Some(self.entries[mid].1)
    } else if cmp < 0 {
      lo = mid + 1
    } else {
      hi = mid - 1
    }
  }
  None
}

///|
/// Reports whether a built-in with validated `name` is registered.
pub fn BuiltinRegistry::contains(
  self : BuiltinRegistry,
  name : BuiltinName,
) -> Bool {
  self.get(name) is Some(_)
}

///|
/// Boundary helper that parses a raw dotted name and looks up its entry,
/// returning `None` if the name is malformed or unregistered.
pub fn BuiltinRegistry::lookup(
  self : BuiltinRegistry,
  raw_name : String,
) -> BuiltinEntry? {
  let parsed = BuiltinName(raw_name) catch { _ => return None }
  self.get(parsed)
}

///|
/// Returns a new immutable registry with `signature` registered (or replaced).
pub fn BuiltinRegistry::with_signature(
  self : BuiltinRegistry,
  signature : BuiltinSignature,
  func : (ReadOnlyArray[@value.Value], BuiltinContext) -> Result[
    @value.Value?,
    BuiltinError,
  ],
) -> BuiltinRegistry {
  self.with_builtin(signature.name(), signature.arity(), func)
}

///|
/// Number of registered built-ins.
pub fn BuiltinRegistry::length(self : BuiltinRegistry) -> Int32 {
  self.entries.length()
}

///|
/// Returns a new immutable registry with `name` registered (or replaced).
pub fn BuiltinRegistry::with_builtin(
  self : BuiltinRegistry,
  name : BuiltinName,
  arity : BuiltinArity,
  func : (ReadOnlyArray[@value.Value], BuiltinContext) -> Result[
    @value.Value?,
    BuiltinError,
  ],
) -> BuiltinRegistry {
  let key = name.to_string()
  let entry : BuiltinEntry = { name, arity, func, }
  let out : Array[(String, BuiltinEntry)] = []
  let mut placed = false
  for pair in self.entries {
    let c = key.compare(pair.0)
    if c == 0 {
      out.push((key, entry))
      placed = true
    } else if !placed && c < 0 {
      out.push((key, entry))
      out.push(pair)
      placed = true
    } else {
      out.push(pair)
    }
  }
  if !placed {
    out.push((key, entry))
  }
  { entries: ReadOnlyArray::from_array(out), }
}

///|
/// Returns the standard Tier-1 pure built-in registry matching OPA v1.23.0.
pub fn BuiltinRegistry::tier1() -> BuiltinRegistry {
  let list : Array[(String, BuiltinEntry)] = []
  register_core_builtins(list)
  register_string_graph_builtins(list)
  BuiltinRegistry::from_entries(list)
}

///|
/// Returns the full pure standard library built-in registry (Tier-1 + Tier-2)
/// matching OPA v1.23.0.
pub fn BuiltinRegistry::standard() -> BuiltinRegistry {
  let list : Array[(String, BuiltinEntry)] = []
  register_core_builtins(list)
  register_string_graph_builtins(list)
  register_tier2_builtins(list)
  BuiltinRegistry::from_entries(list)
}

///|
fn register_tier2_builtins(list : Array[(String, BuiltinEntry)]) -> Unit {
  register_encoding_uri_builtins(list)
  register_semver_units_builtins(list)
  register_regex_builtins(list)
  register_glob_builtins(list)
  register_time_builtins(list)
  register_rand_uuid_template_ast_builtins(list)
}