"""独立示例：属性优先级、无副作用观测与缓存失效。"""
from functools import cached_property
import inspect


class Positive:
    def __set_name__(self, owner, name):
        self.storage_name = "_" + name

    def __get__(self, instance, owner=None):
        if instance is None:
            return self
        return vars(instance)[self.storage_name]

    def __set__(self, instance, value):
        if type(value) is not int or value <= 0:
            raise ValueError("limit must be a positive integer")
        vars(instance)[self.storage_name] = value


class Report:
    limit = Positive()

    def __init__(self, limit):
        self.limit = limit

    def title(self):
        return "report"

    def __getattr__(self, name):
        if name == "optional":
            return "fallback"
        raise AttributeError(name)


if __name__ == "__main__":
    report = Report(10)
    report.__dict__["limit"] = -1  # 反例：试图遮蔽数据描述符。
    assert report.limit == 10
    print("validated:", report.limit)
    try:
        report.limit = 0
    except ValueError as exc:
        print("rejected:", str(exc))
    report.title = "instance value"  # 函数是非数据描述符，可以被遮蔽。
    assert report.title == "instance value"
    print("shadow:", report.title)
    print("fallback:", report.optional)

    class CachedReport:
        def __init__(self):
            self.rows = ["ok"]
            self.calls = 0

        @cached_property
        def count(self):
            self.calls += 1
            return len(self.rows)

    cached = CachedReport()
    candidate = inspect.getattr_static(cached, "count")
    assert isinstance(candidate, cached_property) and cached.calls == 0
    assert getattr(cached, "count") == 1 and cached.calls == 1
    cached.rows.append("error")
    assert cached.count == 1 and cached.calls == 1  # 反例：底层变了，缓存未失效。
    del cached.count  # 正例：明确删除缓存；下一次读取重新计算。
    assert cached.count == 2 and cached.calls == 2
    print("static read calls:", 0, "after invalidation:", cached.count, cached.calls)

    class MissingReport:
        limit = Positive()

    try:
        MissingReport().limit
    except KeyError:
        print("missing storage:", "KeyError (minimal descriptor boundary)")

    class RequiredPositive(Positive):
        def __get__(self, instance, owner=None):
            if instance is None:
                return self
            try:
                return super().__get__(instance, owner)
            except KeyError as error:
                raise AttributeError("required field not initialized") from error

    class RequiredReport:
        limit = RequiredPositive()

    assert not hasattr(RequiredReport(), "limit")
    print("missing field:", "AttributeError preserved")
