///|
pub(all) struct ReliabilityRun {
  id : String
  target : SloTarget
  window : RequestWindow
} derive(Eq, Debug)

///|
pub fn ReliabilityRun::new(
  id : String,
  target : SloTarget,
  window : RequestWindow,
) -> ReliabilityRun {
  { id, target, window }
}

///|
pub(all) struct ReliabilityResult {
  id : String
  budget : BudgetReport
  burn : BurnReport
  label : String
  recommendation : String
} derive(Eq, Debug)

///|
pub fn ReliabilityRun::evaluate(self : ReliabilityRun) -> ReliabilityResult {
  let budget = evaluate_budget(self.target, self.window)
  let burn = calculate_burn_rate(self.target, self.window)
  let label = if !budget.healthy() {
    "budget_exhausted"
  } else if burn.burn_rate_x100 >= 100 {
    "elevated_burn"
  } else {
    "healthy"
  }
  let recommendation = match label {
    "budget_exhausted" => "pause rollout and investigate errors"
    "elevated_burn" => "continue with heightened monitoring"
    _ => "release may proceed"
  }
  { id: self.id, budget, burn, label, recommendation }
}

///|
pub fn ReliabilityResult::approved(self : ReliabilityResult) -> Bool {
  self.label == "healthy"
}

///|
pub fn ReliabilityResult::to_json(self : ReliabilityResult) -> String {
  "{\"id\":\"\{escape_json(self.id)}\",\"label\":\"\{self.label}\",\"recommendation\":\"\{self.recommendation}\",\"budget\":\{self.budget.to_json()},\"burn\":\{self.burn.to_json()}}"
}

///|
pub fn evaluate_release_readiness(
  target : SloTarget,
  current : RequestWindow,
  recent : Array[RequestWindow],
) -> ReliabilityResult {
  let current_result = ReliabilityRun::new("release", target, current).evaluate()
  let stats = WindowStatistics::from_windows(recent)
  if !stats.healthy(target) && current_result.label == "healthy" {
    {
      ..current_result,
      label: "recent_degradation",
      recommendation: "hold release and inspect recent windows",
    }
  } else {
    current_result
  }
}

///|
pub fn ReliabilityResult::status_line(self : ReliabilityResult) -> String {
  "\{self.id}: \{self.label} - \{self.recommendation}"
}

///|
pub fn health_label(healthy : Bool) -> String {
  if healthy {
    "healthy"
  } else {
    "unhealthy"
  }
}