"""Exercise every helper in helpers.py, including the failure cases."""
import logging

from helpers import TIMINGS, cached, managed, retry, timer

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")

attempts = []


@retry(attempts=3, exceptions=(ConnectionError,), sleep=None)
def flaky():
    attempts.append(1)
    if len(attempts) < 3:
        raise ConnectionError("connection reset")
    return "got the data"


@cached(maxsize=32)
def price_of(sku):
    lookups.append(sku)
    return {"A-1": 9.99, "B-2": 24.50}.get(sku, 0.0)


@timer
def summarize(rows):
    return sum(rows) / len(rows)


class Handle:
    def __init__(self):
        self.open = True

    def close(self):
        self.open = False


if __name__ == "__main__":
    print("retry:", flaky(), "after", len(attempts), "attempts")

    lookups = []
    for sku in ["A-1", "B-2", "A-1", "A-1"]:
        price_of(sku)
    print("cache:", price_of.cache_info())

    print("timer:", summarize([2, 4, 6]), "->", len(TIMINGS["summarize"]), "call recorded")

    handle = Handle()
    try:
        with managed(handle):
            raise ValueError("boom")
    except ValueError:
        pass
    print("managed: closed even after an error ->", not handle.open)
