#[cfg(not(coverage))]
#[derive(Clone, Copy, Debug)]
enum UplinkDropReason {
    QueueFull,
    Stale,
}

#[cfg(not(coverage))]
#[derive(Debug)]
struct UplinkDropLogLimiter {
    stream: &'static str,
    icon: &'static str,
    last_warn_at: Option<Instant>,
    suppressed_full: u64,
    suppressed_stale: u64,
}

#[cfg(not(coverage))]
/// Aggregate freshness-first upstream drops into periodic warnings per stream.
impl UplinkDropLogLimiter {
    fn new(stream: &'static str, icon: &'static str) -> Self {
        Self {
            stream,
            icon,
            last_warn_at: None,
            suppressed_full: 0,
            suppressed_stale: 0,
        }
    }

    /// Fold full-queue and stale-packet drops into one periodic warning.
    fn record(&mut self, reason: UplinkDropReason, count: u64, queue_depth: usize, age_ms: f32) {
        match reason {
            UplinkDropReason::QueueFull => {
                self.suppressed_full = self.suppressed_full.saturating_add(count)
            }
            UplinkDropReason::Stale => {
                self.suppressed_stale = self.suppressed_stale.saturating_add(count)
            }
        }

        let should_warn = self
            .last_warn_at
            .map(|last| last.elapsed() >= UPLINK_DROP_WARN_INTERVAL)
            .unwrap_or(true);
        if should_warn {
            warn!(
                stream = self.stream,
                dropped_queue_full = self.suppressed_full,
                dropped_stale = self.suppressed_stale,
                queue_depth,
                latest_age_ms = age_ms,
                "{} upstream {} queue is dropping stale/superseded packets to preserve live A/V sync",
                self.icon,
                self.stream
            );
            self.suppressed_full = 0;
            self.suppressed_stale = 0;
            self.last_warn_at = Some(Instant::now());
        } else {
            debug!(
                stream = self.stream,
                ?reason,
                count,
                queue_depth,
                latest_age_ms = age_ms,
                "upstream media queue drop suppressed from WARN noise"
            );
        }
    }
}

#[cfg(not(coverage))]
const UPLINK_DROP_WARN_INTERVAL: Duration = Duration::from_secs(5);

#[cfg(not(coverage))]
/// Report an upstream queue drop through the shared rate limiter.
fn log_uplink_drop(
    limiter: &Arc<std::sync::Mutex<UplinkDropLogLimiter>>,
    reason: UplinkDropReason,
    count: u64,
    queue_depth: usize,
    age_ms: f32,
) {
    if let Ok(mut limiter) = limiter.lock() {
        limiter.record(reason, count, queue_depth, age_ms);
    }
}
