"""独立示例：缓存上下文遗漏与 wraps。"""
from functools import lru_cache, wraps
import inspect


current_tenant = "alpha"


@lru_cache(maxsize=16)
def bad_lookup(report_id):
    return f"{current_tenant}:{report_id}"


def trace(function):
    @wraps(function)
    def wrapper(*args, **kwargs):
        print("call:", function.__name__)
        return function(*args, **kwargs)
    return wrapper


@trace
@lru_cache(maxsize=16)
def lookup(tenant, report_id):
    return f"{tenant}:{report_id}"


if __name__ == "__main__":
    assert bad_lookup(7) == "alpha:7"
    current_tenant = "beta"
    print("bad:", bad_lookup(7))  # 同一个键，错误地复用 alpha 的结果。
    assert bad_lookup(7) == "alpha:7"
    print("good:", lookup("alpha", 7), lookup("beta", 7))
    print("name:", lookup.__name__)
    print("signature:", inspect.signature(lookup))

    def exercise(cache_outside):
        observations = {"trace": 0, "origin": 0}

        def origin(key):
            observations["origin"] += 1
            return key * 2

        def counted_trace(function):
            @wraps(function)
            def wrapper(*args, **kwargs):
                observations["trace"] += 1
                return function(*args, **kwargs)
            return wrapper

        if cache_outside:
            wrapped = lru_cache(maxsize=4)(counted_trace(origin))
            cached_function = wrapped
        else:
            cached_function = lru_cache(maxsize=4)(origin)
            wrapped = counted_trace(cached_function)
        assert wrapped(7) == wrapped(7) == 14
        info = cached_function.cache_info()
        assert (info.hits, info.misses, observations["origin"]) == (1, 1, 1)
        return observations, info

    outer_trace, trace_cache = exercise(False)
    outer_cache, cache_trace = exercise(True)
    assert outer_trace["trace"] == 2 and outer_cache["trace"] == 1
    print("order trace/cache:", outer_trace, trace_cache)
    print("order cache/trace:", outer_cache, cache_trace)

    receipts = []
    attempts = 0

    def committed_but_response_lost():
        global attempts
        attempts += 1
        receipts.append("receipt")  # 模拟成功副作用；不是实际支付或网络调用。
        if attempts == 1:
            raise ConnectionError("response lost after commit")
        return "ok"

    for attempt in range(2):
        try:
            committed_but_response_lost()
            break
        except ConnectionError:
            if attempt == 1:
                raise
    assert len(receipts) == 2
    print("unsafe retry receipts:", len(receipts))
