# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-invariants-prevent-a-monotonic-counter-wrap-from-regressing-sequence-order.md
# Remnant Warrant:    https://corpusfetch.com/c/what-invariants-prevent-a-monotonic-counter-wrap-from-regressing-sequence-order.warrant.json
# Markdown SHA-256:   92b433ee8d4b37743128c8d5d1a36d22a010a791a1ee13b9384a9edb3ec3b4d7
# Code AST SHA-256:   6e8a9b601cc092766dc08213d7b454fc65ff0fec095e25ff0f66aaa7cfcee082
# Verified Classes:   CounterWrapError, CounterGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CounterWrapError(RuntimeError):
    """Raised when a counter's width cannot absorb expected lifetime traffic."""


@dataclass(frozen=True)
class CounterGate:
    bit_width: int
    observed_rate: int
    expected_lifetime_s: int
    safety_factor: float = 10.0

    def verify(self) -> bool:
        capacity = 2 ** self.bit_width
        expected = self.observed_rate * self.expected_lifetime_s * self.safety_factor
        if expected >= capacity:
            raise CounterWrapError(
                f"expected {int(expected)} >= capacity {capacity}: wrap within lifetime for width {self.bit_width}"
            )
        return True


def dispatch_counter_mode(gate: CounterGate) -> str:
    try:
        gate.verify()
    except CounterWrapError:
        return "wrap-aware-reader"
    return "plain"
