"""独立示例：有界文件流与生成器生命周期。"""
from pathlib import Path
from tempfile import TemporaryDirectory
import tracemalloc


def errors(path, observation=None):
    with path.open(encoding="utf-8") as source:
        if observation is not None:
            observation["file"] = source
            observation["produced"] = 0
        for line in source:
            level, message = line.rstrip("\n").split(" ", 1)
            if level == "ERROR":
                if observation is not None:
                    observation["produced"] += 1
                yield message  # 暂停在这里，文件仍然打开。


def count_levels(path, materialize):
    result = {}
    with path.open(encoding="utf-8") as source:
        rows = source.readlines() if materialize else source
        for line in rows:
            level = line.split(" ", 1)[0]
            result[level] = result.get(level, 0) + 1
    return result


def measured_counts(path, materialize):
    tracemalloc.start()
    try:
        result = count_levels(path, materialize)
        current, peak = tracemalloc.get_traced_memory()
        return result, current, peak
    finally:
        tracemalloc.stop()


if __name__ == "__main__":
    with TemporaryDirectory() as directory:
        path = Path(directory) / "demo.log"
        path.write_text("INFO boot\nERROR timeout\nERROR reset\n", encoding="utf-8")
        stream = errors(path)
        first = list(stream)  # 教学反例：全量物化，并耗尽一次性迭代器。
        second = list(stream)
        assert first == ["timeout", "reset"] and second == []
        print("consumed:", first, second)
        counts = {}
        for message in errors(path):  # 正例：重新创建流并逐条聚合。
            counts[message] = counts.get(message, 0) + 1
        print("counts:", counts)
        observation = {}
        partial = errors(path, observation)
        assert next(partial) == "timeout"
        assert not observation["file"].closed and observation["produced"] == 1
        partial.close()  # 提前停止时显式释放生成器内的文件。
        assert list(partial) == []
        assert observation["file"].closed
        print("closed:", observation["file"].closed, "produced:", observation["produced"])
        path.write_text("ERROR " + "x" * 1024 + "\n", encoding="utf-8")
        with path.open("a", encoding="utf-8") as target:
            for index in range(255):
                target.write(("INFO" if index % 2 else "ERROR") + " " + "x" * 1024 + "\n")
        materialized, materialized_current, materialized_peak = measured_counts(path, True)
        streamed, streamed_current, streamed_peak = measured_counts(path, False)
        assert materialized == streamed and sum(streamed.values()) == 256
        # 只判断本实验固定数据的峰值关系，不宣称所有输入都有相同比例。
        assert streamed_peak < materialized_peak
        print("traced bytes current/peak:", (materialized_current, materialized_peak),
              (streamed_current, streamed_peak))
        path.write_text("ERROR first\nbroken\n", encoding="utf-8")
        failed_observation = {}
        published = None
        try:
            collected = list(errors(path, failed_observation))
            published = collected  # 只有完整消费成功才发布完整结果。
        except ValueError:
            pass
        assert published is None and failed_observation["file"].closed
        print("partial result published:", published, "closed after error:",
              failed_observation["file"].closed)
