///|
pub(all) suberror DoctorError {
  DoctorError(String)
}

///|
/// A run snapshot supplied by the caller; no ambient environment is read here.
pub(all) struct Context {
  facts : Map[String, String]
  allow_network : Bool
}

///|
pub fn context(
  facts~ : Map[String, String] = {},
  allow_network~ : Bool = false,
) -> Context {
  { facts, allow_network, }
}

///|
pub(all) struct Rule {
  id : String
  name : String
  category : String
  severity : Severity
  priority : Int32
  dependencies : Array[String]
  enabled : Bool
  timeout_ms : Int32
  execute : async (Context) -> Finding
}

///|
pub fn rule(
  id : String,
  category : String,
  execute : async (Context) -> Finding,
  name~ : String = "",
  severity~ : Severity = Medium,
  priority~ : Int32 = 100,
  dependencies~ : Array[String] = [],
  enabled~ : Bool = true,
  timeout_ms~ : Int32 = 3000,
) -> Rule {
  {
    id,
    name: if name == "" {
      id
    } else {
      name
    },
    category,
    execute,
    severity,
    priority,
    dependencies,
    enabled,
    timeout_ms,
  }
}

///|
pub struct Registry {
  rules : Array[Rule]
  max_rules : Int32
}

///|
pub fn Registry::new(max_rules~ : Int32 = 256) -> Registry raise DoctorError {
  if max_rules < 1 || max_rules > 4096 {
    raise DoctorError("rule limit must be between 1 and 4096")
  }
  { rules: [], max_rules, }
}

///|
fn valid_id(id : String) -> Bool {
  id.length() > 0 &&
  id.length() <= 128 &&
  id
  .iter()
  .all(c => {
    c.is_ascii_alphabetic() ||
    c.is_ascii_digit() ||
    c == '.' ||
    c == '_' ||
    c == '-'
  })
}

///|
pub fn Registry::register(
  self : Registry,
  value : Rule,
) -> Unit raise DoctorError {
  if !valid_id(value.id) || !valid_id(value.category) {
    raise DoctorError("invalid rule identifier or category")
  }
  if self.rules.length() >= self.max_rules {
    raise DoctorError("rule limit exceeded")
  }
  if self.get(value.id) is Some(_) {
    raise DoctorError("duplicate rule: \{value.id}")
  }
  if value.timeout_ms < 1 || value.timeout_ms > 60000 {
    raise DoctorError("rule timeout must be between 1 and 60000 ms")
  }
  self.rules.push({ ..value, dependencies: value.dependencies.copy(), })
}

///|
pub fn Registry::get(self : Registry, id : String) -> Rule? {
  self.rules
  .search_by(r => r.id == id)
  .map(i => {
    ..self.rules[i],
    dependencies: self.rules[i].dependencies.copy(),
  })
}

///|
pub fn Registry::list(self : Registry) -> Array[Rule] {
  self.rules.map(r => { ..r, dependencies: r.dependencies.copy(), })
}

///|
pub fn Registry::unregister(
  self : Registry,
  id : String,
) -> Unit raise DoctorError {
  let index = self.rules.search_by(r => r.id == id)
  match index {
    Some(i) => self.rules.remove(i) |> ignore
    None => raise DoctorError("unknown rule: \{id}")
  }
}

///|
pub fn Registry::set_enabled(
  self : Registry,
  id : String,
  enabled : Bool,
) -> Unit raise DoctorError {
  match self.rules.search_by(r => r.id == id) {
    Some(i) => self.rules[i] = { ..self.rules[i], enabled, }
    None => raise DoctorError("unknown rule: \{id}")
  }
}