"""
Solution: what a cache buys and how it breaks. Lab 08's logic for scripts 01_hit_ratio.py,
02_cache_speedup.py and 04_stampede.py (cache_sim.py, cache_metrics.py and
service/cache_logic.py), in plain Python.
"""
import math
from collections import OrderedDict


def top_share(n, s, k):
    """The share of requests the k most popular of n items get, when the item ranked r is asked
    for in proportion to 1 / r**s (a Zipf distribution). The best any cache of k items can do."""
    weights = [1 / r ** s for r in range(1, n + 1)]
    return sum(weights[:k]) / sum(weights)


def lru_hits(stream, capacity, warmup=0):
    """Run a stream of keys through a cache that throws out the least recently used key when
    full (cache-aside: a miss puts the key in). Return the hits after the first `warmup` requests."""
    cache = OrderedDict()
    hits = 0
    for i, key in enumerate(stream):
        if key in cache:
            cache.move_to_end(key)
            if i >= warmup:
                hits += 1
            continue
        cache[key] = None
        if len(cache) > capacity:
            cache.popitem(last=False)
    return hits


def lfu_hits(stream, capacity, warmup=0):
    """Same, but throw out the least frequently used key; on a tie, the least recently used of
    those. A new key starts with a count of 1."""
    count = {}
    last = {}
    hits = 0
    for i, key in enumerate(stream):
        if key in count:
            count[key] += 1
            last[key] = i
            if i >= warmup:
                hits += 1
            continue
        if len(count) >= capacity:
            victim = min(count, key=lambda k: (count[k], last[k]))
            del count[victim], last[victim]
        count[key] = 1
        last[key] = i
    return hits


def db_reads_per_s(rate, hit_ratio):
    """Reads a second that reach the database: only the misses."""
    return (1 - hit_ratio) * rate


def half_second_steps(rates_100ms):
    """Average each 5 bins of 100 ms into half-second steps."""
    return [sum(rates_100ms[i:i + 5]) / 5 for i in range(0, len(rates_100ms) - 4, 5)]


def jittered_ttl(ttl_ms, jitter, u):
    """TTL jitter: ttl_ms times a factor spread evenly over [1 - jitter, 1 + jitter].
    u in [0, 1] picks the factor (0 gives the shortest, 1 the longest). Round to whole ms, at
    least 1. Raise ValueError unless 0 <= jitter < 1."""
    if not 0 <= jitter < 1:
        raise ValueError("jitter must be in [0, 1)")
    return max(1, round(ttl_ms * (1 + (2 * u - 1) * jitter)))


def xfetch_should_refresh(delta_s, expiry, now, beta, u):
    """Early refresh (XFetch): refresh now if now - delta_s * beta * ln(u) >= expiry.
    delta_s: how long the last recompute took. u: a random number in (0, 1]."""
    return now - delta_s * beta * math.log(u) >= expiry


def recomputes_per_expiry(recomputes, seconds, ttl_s):
    """Recomputes divided by the number of expiries in a run: seconds / ttl_s, rounded, at least 1."""
    return recomputes / max(1, round(seconds / ttl_s))
