"""Function, decorator and closure snippets."""
import functools
import time


def compose(*fns):
    """Right-to-left function composition: compose(f, g)(x) == f(g(x)).

    >>> inc_then_double = compose(lambda x: x * 2, lambda x: x + 1)
    >>> inc_then_double(5)
    12
    """
    return functools.reduce(lambda f, g: lambda *a, **k: f(g(*a, **k)), fns)


def pipe(value, *fns):
    """Pass a value through functions left to right.

    >>> pipe('  Hello ', str.strip, str.upper, len)
    5
    """
    for fn in fns:
        value = fn(value)
    return value


def once(fn):
    """Decorator: run ``fn`` only the first time; later calls return the first result.

    >>> @once
    ... def init():
    ...     print('setting up')
    ...     return 42
    >>> init()
    setting up
    42
    >>> init()
    42
    """
    result = []

    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        if not result:
            result.append(fn(*args, **kwargs))
        return result[0]
    return wrapper


def retry(times=3, exceptions=(Exception,), delay=0.0, backoff=2.0):
    """Decorator: retry on the given exceptions with exponential backoff.

    >>> calls = []
    >>> @retry(times=3)
    ... def flaky():
    ...     calls.append(1)
    ...     if len(calls) < 3:
    ...         raise ConnectionError('try again')
    ...     return 'ok'
    >>> flaky(), len(calls)
    ('ok', 3)
    """
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            wait = delay
            for attempt in range(1, times + 1):
                try:
                    return fn(*args, **kwargs)
                except exceptions:
                    if attempt == times:
                        raise
                    if wait:
                        time.sleep(wait)
                    wait *= backoff
        return wrapper
    return decorator


def timed(fn):
    """Decorator: store the last run time (seconds) on ``wrapper.last_seconds``.

    >>> @timed
    ... def work():
    ...     return sum(range(1000))
    >>> work()
    499500
    >>> work.last_seconds >= 0
    True
    """
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return fn(*args, **kwargs)
        finally:
            wrapper.last_seconds = time.perf_counter() - start
    wrapper.last_seconds = None
    return wrapper


def memoize(fn):
    """Cache results by arguments. For real code prefer functools.cache.

    >>> @memoize
    ... def fib(n):
    ...     return n if n < 2 else fib(n - 1) + fib(n - 2)
    >>> fib(80)
    23416728348467685
    """
    cache = {}

    @functools.wraps(fn)
    def wrapper(*args):
        if args not in cache:
            cache[args] = fn(*args)
        return cache[args]
    wrapper.cache = cache
    return wrapper


def ttl_cache(seconds, clock=time.monotonic):
    """Decorator: cache results for ``seconds`` before recomputing.

    >>> now = [0.0]
    >>> @ttl_cache(10, clock=lambda: now[0])
    ... def stamp():
    ...     return now[0]
    >>> stamp(); now[0] = 5; stamp(); now[0] = 11; stamp()
    0.0
    0.0
    11
    """
    def decorator(fn):
        cache = {}

        @functools.wraps(fn)
        def wrapper(*args):
            hit = cache.get(args)
            if hit and clock() - hit[0] < seconds:
                return hit[1]
            value = fn(*args)
            cache[args] = (clock(), value)
            return value
        return wrapper
    return decorator


def curry(fn, arity=None):
    """Call a function one argument (or a few) at a time.

    >>> add3 = curry(lambda a, b, c: a + b + c)
    >>> add3(1)(2)(3), add3(1, 2)(3)
    (6, 6)
    """
    import inspect
    arity = arity or len(inspect.signature(fn).parameters)

    def curried(*args):
        if len(args) >= arity:
            return fn(*args)
        return lambda *more: curried(*args, *more)
    return curried


def rate_limited(calls_per_second, clock=time.monotonic, sleep=time.sleep):
    """Decorator: space calls so they never exceed ``calls_per_second``.

    >>> t = [0.0]
    >>> slept = []
    >>> @rate_limited(2, clock=lambda: t[0], sleep=slept.append)
    ... def ping():
    ...     return 'pong'
    >>> ping(), ping(), slept
    ('pong', 'pong', [0.5])
    """
    interval = 1.0 / calls_per_second

    def decorator(fn):
        last = [None]

        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            now = clock()
            if last[0] is not None:
                wait = interval - (now - last[0])
                if wait > 0:
                    sleep(wait)
                    now += wait
            last[0] = now
            return fn(*args, **kwargs)
        return wrapper
    return decorator
