import time


def track_rate(*, current, last_recorded, last_recorded_time, metric_name, min_increase=1_000_000, stats):
    """Calculates rate of change given current value and previously handled value and time. If there is
    a relevant change (as defined by min_increase) and some time has passed, the current rate of change
    is sent as integer gauge using given stats client and metric name. Returns the values to pass to the
    next invocation of this function."""
    now = time.monotonic()
    return_value, return_time = last_recorded, last_recorded_time
    if current > last_recorded + min_increase and now > last_recorded_time:
        time_elapsed = now - last_recorded_time
        diff = current - last_recorded
        per_second = int(diff / time_elapsed)
        if per_second > 0:
            stats.gauge_int(metric_name, per_second)
            return_value = current
            return_time = now
    return return_value, return_time