///|
/// A capability that was not tested is never a passing diagnosis.
pub(all) enum Status {
  Passed
  Warning
  Failed
  Skipped
  Unsupported
  Error
} derive(Eq)

///|
pub extend Status with Eq::{equal, not_equal}

///|
pub fn Status::label(self : Status) -> String {
  match self {
    Passed => "passed"
    Warning => "warning"
    Failed => "failed"
    Skipped => "skipped"
    Unsupported => "unsupported"
    Error => "error"
  }
}

///|
pub(all) enum Severity {
  Info
  Low
  Medium
  High
  Critical
}

///|
pub fn Severity::label(self : Severity) -> String {
  match self {
    Info => "info"
    Low => "low"
    Medium => "medium"
    High => "high"
    Critical => "critical"
  }
}

///|
pub(all) struct Evidence {
  key : String
  value : String
  sensitive : Bool
}

///|
pub(all) struct Finding {
  status : Status
  code : String
  message : String
  evidence : Array[Evidence]
  remediation : String
}

///|
/// Construct a finding. Evidence should contain observations, never credentials.
pub fn finding(
  status : Status,
  code : String,
  message : String,
  evidence~ : Array[Evidence] = [],
  remediation~ : String = "",
) -> Finding {
  {
    status,
    code,
    message,
    evidence,
    remediation: if remediation.is_empty() {
      remediation_for(code)
    } else {
      remediation
    },
  }
}

///|
pub(all) struct DiagnosticResult {
  rule_id : String
  category : String
  severity : Severity
  finding : Finding
  duration_ms : Int64
}

///|
pub(all) struct Summary {
  passed : Int32
  warning : Int32
  failed : Int32
  skipped : Int32
  unsupported : Int32
  errors : Int32
}

///|
pub fn summarize(results : Array[DiagnosticResult]) -> Summary {
  let counts = [0, 0, 0, 0, 0, 0]
  for result in results {
    let i = match result.finding.status {
      Passed => 0
      Warning => 1
      Failed => 2
      Skipped => 3
      Unsupported => 4
      Error => 5
    }
    counts[i] += 1
  }
  {
    passed: counts[0],
    warning: counts[1],
    failed: counts[2],
    skipped: counts[3],
    unsupported: counts[4],
    errors: counts[5],
  }
}

///|
/// Exit code 2 denotes execution errors; 1 denotes diagnosed failures; 0 otherwise.
pub fn Summary::exit_code(self : Summary, strict~ : Bool = false) -> Int32 {
  if self.errors > 0 {
    2
  } else if self.failed > 0 ||
    (strict && (self.warning > 0 || self.unsupported > 0 || self.skipped > 0)) {
    1
  } else {
    0
  }
}