///|
/// Immutable filter selecting which discovered Rego `test_*` / `todo_test_*`
/// rules `run_tests` executes.
#derive(Eq, Hash, Debug)
struct TestFilter {
  prefix : String?
}

///|
/// Matches every discovered `test_*` and `todo_test_*` rule.
pub fn TestFilter::all() -> TestFilter {
  { prefix: None, }
}

///|
/// Matches test rules whose qualified path (`data..`) starts with
/// `prefix`. A leading `"data."` is added automatically when omitted; an empty
/// string matches all tests.
pub fn TestFilter::prefix(prefix : String) -> TestFilter {
  if prefix.is_empty() {
    { prefix: None, }
  } else if prefix.has_prefix("data.") {
    { prefix: Some(prefix), }
  } else {
    { prefix: Some("data.\{prefix}"), }
  }
}

///|
/// Returns the normalized prefix text, or `None` when matching all tests.
pub fn TestFilter::prefix_text(self : TestFilter) -> String? {
  self.prefix
}

///|
/// Reports whether `qualified_name` (`data..`) matches this filter.
pub fn TestFilter::matches(self : TestFilter, qualified_name : String) -> Bool {
  match self.prefix {
    None => true
    Some(p) => qualified_name.has_prefix(p)
  }
}

///|
/// Outcome of one Rego `test_*` or `todo_test_*` rule evaluation.
#derive(Eq, Debug)
pub(all) enum TestStatus {
  /// Test rule evaluated to a defined non-`false` value.
  Pass
  /// Test rule evaluated to `false` or was undefined.
  Fail
  /// Test rule was prefixed with `todo_test_` and skipped without executing.
  Skip
  /// Test rule raised a runtime `EvalError` (for example `BudgetExceeded` or `Conflict`).
  Error(@vm.EvalError)
}

///|
pub impl Show for TestStatus with fn output(self, logger) {
  match self {
    Pass => logger.write_string("PASS")
    Fail => logger.write_string("FAIL")
    Skip => logger.write_string("SKIP")
    Error(err) => {
      logger.write_string("ERROR(")
      Show::output(err, logger)
      logger.write_string(")")
    }
  }
}

///|
/// Immutable result of one discovered Rego test rule.
#derive(Eq, Debug)
struct TestCaseResult {
  package_path : String
  rule_name : String
  qualified_name : String
  status : TestStatus
}

///|
/// Returns the dotted package path (for example `"data.auth"`).
pub fn TestCaseResult::package_path(self : TestCaseResult) -> String {
  self.package_path
}

///|
/// Returns the test rule name (for example `"test_admin_allowed"`).
pub fn TestCaseResult::rule_name(self : TestCaseResult) -> String {
  self.rule_name
}

///|
/// Returns the fully qualified rule path (for example `"data.auth.test_admin_allowed"`).
pub fn TestCaseResult::qualified_name(self : TestCaseResult) -> String {
  self.qualified_name
}

///|
/// Returns the outcome status of this test case.
pub fn TestCaseResult::status(self : TestCaseResult) -> TestStatus {
  self.status
}

///|
/// Reports whether this test case passed.
pub fn TestCaseResult::is_passed(self : TestCaseResult) -> Bool {
  self.status is Pass
}

///|
/// Reports whether this test case failed.
pub fn TestCaseResult::is_failed(self : TestCaseResult) -> Bool {
  self.status is Fail
}

///|
/// Reports whether this test case was skipped (`todo_test_*`).
pub fn TestCaseResult::is_skipped(self : TestCaseResult) -> Bool {
  self.status is Skip
}

///|
/// Reports whether this test case raised a runtime error.
pub fn TestCaseResult::is_error(self : TestCaseResult) -> Bool {
  self.status is Error(_)
}

///|
/// Immutable aggregate report returned by `run_tests`.
#derive(Eq, Debug)
struct TestReport {
  results : ReadOnlyArray[TestCaseResult]
}

///|
/// Returns all executed and skipped test case results in deterministic sorted order.
pub fn TestReport::results(self : TestReport) -> ReadOnlyArray[TestCaseResult] {
  self.results
}

///|
/// Total number of test cases included in this report.
pub fn TestReport::total_count(self : TestReport) -> Int32 {
  self.results.length()
}

///|
/// Number of test cases with `TestStatus::Pass`.
pub fn TestReport::passed_count(self : TestReport) -> Int32 {
  let mut count = 0
  for r in self.results {
    if r.is_passed() {
      count += 1
    }
  }
  count
}

///|
/// Number of test cases with `TestStatus::Fail`.
pub fn TestReport::failed_count(self : TestReport) -> Int32 {
  let mut count = 0
  for r in self.results {
    if r.is_failed() {
      count += 1
    }
  }
  count
}

///|
/// Number of test cases with `TestStatus::Skip`.
pub fn TestReport::skipped_count(self : TestReport) -> Int32 {
  let mut count = 0
  for r in self.results {
    if r.is_skipped() {
      count += 1
    }
  }
  count
}

///|
/// Number of test cases with `TestStatus::Error`.
pub fn TestReport::error_count(self : TestReport) -> Int32 {
  let mut count = 0
  for r in self.results {
    if r.is_error() {
      count += 1
    }
  }
  count
}

///|
/// Reports whether zero test cases failed or errored (skipped tests do not fail a report).
pub fn TestReport::all_passed(self : TestReport) -> Bool {
  for r in self.results {
    if r.is_failed() || r.is_error() {
      return false
    }
  }
  true
}

///|
fn join_data_path(segments : ArrayView[String]) -> String {
  let buf = StringBuilder()
  buf.write_string("data")
  for seg in segments {
    buf.write_char('.')
    buf.write_string(seg)
  }
  buf.to_string()
}

///|
/// Pure zero-I/O Rego unit test runner. Discovers every `test_*` and
/// `todo_test_*` rule in `policy`, evaluates each matching test under its own
/// isolated `StepBudget` and `EngineOptions`, and returns an immutable `TestReport`.
pub fn run_tests(
  policy : @compile.CompiledPolicy,
  data~ : @value.Value = @value.Value::Object(@value.RegoObject::empty()),
  options~ : @vm.EngineOptions = @vm.EngineOptions::default(),
  filter~ : TestFilter = TestFilter::all(),
) -> TestReport {
  let discovered : Array[(String, String, String, ReadOnlyArray[String])] = []
  for path in policy.rule_paths() {
    if path.length() < 2 {
      continue
    }
    let rule_name = path[path.length() - 1]
    let is_test = rule_name.has_prefix("test_")
    let is_todo = rule_name.has_prefix("todo_test_")
    if !is_test && !is_todo {
      continue
    }
    // Skip parameterized functions whose names happen to start with `test_`.
    if policy.lookup_node(path[:]) is Some(Function(..)) {
      continue
    }
    let pkg_segs : Array[String] = []
    for i in 0..<(path.length() - 1) {
      pkg_segs.push(path[i])
    }
    let pkg_path = join_data_path(pkg_segs[:])
    let qualified = "\{pkg_path}.\{rule_name}"
    if filter.matches(qualified) {
      discovered.push((qualified, pkg_path, rule_name, path))
    }
  }
  discovered.sort_by((a, b) => a.0.lexical_compare(b.0))

  let results : Array[TestCaseResult] = []
  for item in discovered {
    let (qualified_name, package_path, rule_name, path) = item
    let status : TestStatus = if rule_name.has_prefix("todo_test_") {
      Skip
    } else {
      let eval_res : Result[@value.Value?, @vm.EvalError] = Ok(
        @vm.eval_rule(policy, path[:], data~, options~),
      ) catch {
        err => Err(err)
      }
      match eval_res {
        Ok(Some(Bool(false))) | Ok(None) => Fail
        Ok(Some(_)) => Pass
        Err(err) => Error(err)
      }
    }
    results.push({ package_path, rule_name, qualified_name, status, })
  }
  { results: ReadOnlyArray::from_array(results), }
}