///|
/// A compact health payload for station telemetry endpoints.
pub struct TelemetryHealth {
  station : String
  channel : String
  timestamp : Double
  sample_count : Int
  sample_rate : Double
  quality_score : Double
  alert_count : Int
  state : String
}

///|
/// Build a telemetry health payload from a quality report and alerts.
pub fn telemetry_health(
  report : StationQualityReport,
  timestamp : Double,
  alerts : Array[MonitoringAlert],
) -> TelemetryHealth {
  let summary = summarize_monitoring_alerts(alerts)
  let state = if summary.critical > 0 {
    "critical"
  } else if report.status == "healthy" {
    "healthy"
  } else {
    "degraded"
  }
  {
    station: report.station,
    channel: report.channel,
    timestamp,
    sample_count: report.sample_count,
    sample_rate: report.sample_rate,
    quality_score: report.score,
    alert_count: alerts.length(),
    state,
  }
}

///|
/// Render a health payload as a compact key-value line.
pub fn telemetry_health_text(health : TelemetryHealth) -> String {
  "station=" +
  health.station +
  " channel=" +
  health.channel +
  " timestamp=" +
  health.timestamp.to_string() +
  " samples=" +
  health.sample_count.to_string() +
  " rate=" +
  health.sample_rate.to_string() +
  " score=" +
  health.quality_score.to_string() +
  " alerts=" +
  health.alert_count.to_string() +
  " state=" +
  health.state
}

///|
/// Return whether telemetry should be accepted by a downstream consumer.
pub fn telemetry_is_acceptable(
  health : TelemetryHealth,
  minimum_score : Double,
) -> Bool {
  health.quality_score >= minimum_score &&
  health.state != "critical" &&
  health.sample_rate > 0.0
}