"""
=============================================================================
Stanford CS144 · 第 4 讲 · 02_reassembler_walkthrough.py —— 一步一步看重组器怎样工作
=============================================================================

【这个脚本要回答的问题】（讲义 §4）
    1. 片段到达时，每个字节在哪里？（用一行字符画出每个字节的状态。）
    2. 窗口是什么？为什么它的右边界由字节流的剩余容量决定？
    3. 那些容易写错的边界情况，正确的行为是什么？为什么？

【怎么读输出】
    字节的状态画成一行，每个字符是一个字节（下标从 0 开始）：
        r 已经被应用读走      # 在字节流里，等应用来读      p 在重组器里暂存（前面还有空洞）
        . 窗口之内，还没收到  x 窗口之外，来了也放不下

【运行方式】
    python3 02_reassembler_walkthrough.py      # 瞬间完成；每次相同
"""

import course_path
course_path.use("lecture01", "lecture03")

from console import print_header, print_table, observations
from stream import BoundedByteStream
from reassembler import IntervalReassembler


def draw(reassembler, stream, total):
    """
    画出每个字节的状态。

    【参数】reassembler：IntervalReassembler；stream：BoundedByteStream；total：流的总长度（只为了画图）
    【返回】字符串，长度 = total
    """
    pending = set()
    for start, chunk in zip(reassembler._starts, reassembler._chunks):
        pending.update(range(start, start + len(chunk)))
    cells = []
    for i in range(total):
        if i < stream.total_read:
            cells.append("r")
        elif i < stream.total_written:
            cells.append("#")
        elif i in pending:
            cells.append("p")
        elif i < reassembler.window_end:
            cells.append(".")
        else:
            cells.append("x")
    return "".join(cells)


def part_a_trace():
    """
    跟踪一个例子：容量 8 的字节流，流的内容是 ABCDEFGHIJKLMNOP（16 字节）。

    【返回】True（所有片段拼回了原文）
    """
    print_header("Part A · 一步一步：容量 8，流是 ABCDEFGHIJKLMNOP")
    text = b"ABCDEFGHIJKLMNOP"
    stream = BoundedByteStream(8)
    r = IntervalReassembler(stream)
    received = bytearray()
    print("  下标      0123456789012345")

    def show(action):
        """打印一步之后的状态。"""
        print(f"  状态      {draw(r, stream, len(text))}    next={r.next_index:<2d} window_end={r.window_end:<2d} "
              f"字节流={stream.buffered} 暂存={r.pending_bytes}   ← {action}")

    show("开始")
    steps = [
        ("insert", 2, b"CD", False),
        ("insert", 6, b"GH", False),
        ("insert", 3, b"DEF", False),
        ("insert", 0, b"AB", False),
        ("insert", 10, b"KL", False),
        ("read", 5, None, None),
        ("insert", 10, b"KL", False),
        ("insert", 8, b"IJ", False),
        ("read", 8, None, None),
        ("insert", 12, b"MNOP", True),
        ("read", 8, None, None),
    ]
    for op, a, b, last in steps:
        if op == "insert":
            r.insert(a, b, last)
            label = f'insert({a}, {b.decode()!r}' + (", 最后一段)" if last else ")")
        else:
            got = stream.read(a)
            received.extend(got)
            label = f"应用 read({a}) → {got.decode()!r}"
        show(label)
    print(f"\n  应用读到：{received.decode()}，流结束：{stream.at_eof}")
    print("\n  第一个 insert(10, 'KL') 被丢弃了：窗口的右边界是 8，那时放不下。腾出空间后重发就进来了。")
    print("  这正是流量控制的来源：窗口告诉发送方'现在别发超过这里的数据'（第 5 讲）。")
    return bytes(received) == text


def check_case(name, operations, expected_output, expected_eof, expected_pending, capacity=10, why=""):
    """
    运行一个边界情况，核对结果，返回表格的一行。

    【参数】name：名字；operations：操作列表，每个是 ("insert", index, data, last) 或 ("read", n)；
        expected_output：应用应该读到的内容；expected_eof：是否应该流结束；
        expected_pending：结束时重组器应该暂存多少字节；capacity：容量；why：原因
    【返回】表格的一行 [名字, 期望, 结果, 为什么]
    【边界】结果不符时抛 AssertionError：这个脚本同时也是一份测试。
    """
    stream = BoundedByteStream(capacity)
    r = IntervalReassembler(stream)
    out = bytearray()
    for op in operations:
        if op[0] == "insert":
            r.insert(op[1], op[2], op[3])
        else:
            out.extend(stream.read(op[1]))
    out.extend(stream.read(capacity))
    eof = stream.at_eof
    assert bytes(out) == expected_output, (name, bytes(out))
    assert eof == expected_eof, (name, eof)
    assert r.pending_bytes == expected_pending, (name, r.pending_bytes)
    result = f"读到 {bytes(out).decode()!r}" + ("，流结束" if eof else "") + (f"，暂存 {r.pending_bytes}" if expected_pending else "")
    return [name, result, why]


def part_b_edge_cases():
    """
    容易写错的边界情况，每一条都实际运行并核对。

    【返回】通过的条数
    """
    print_header("Part B · 边界情况：每一条都实际运行并核对过")
    cases = [
        check_case("完全重复", [("insert", 0, b"ab", False), ("insert", 0, b"ab", False)], b"ab", False, 0,
                   why="已经写过的字节不能再写"),
        check_case("部分重叠旧数据", [("insert", 0, b"abc", False), ("insert", 1, b"bcde", False)], b"abcde", False, 0,
                   why="重传的切法可能不同：要裁掉旧的部分，留下新的部分"),
        check_case("新片段盖住多个旧片段", [("insert", 1, b"b", False), ("insert", 3, b"d", False), ("insert", 0, b"abcde", False)],
                   b"abcde", False, 0, why="合并时只算一次"),
        check_case("暂存区里的重叠", [("insert", 2, b"cd", False), ("insert", 3, b"de", False)], b"", False, 3,
                   why="暂存 3 字节（c、d、e），不是 4 字节"),
        check_case("相邻但不重叠", [("insert", 2, b"cd", False), ("insert", 4, b"ef", False), ("insert", 0, b"ab", False)],
                   b"abcdef", False, 0, why="相邻的段也要合并，否则写完一段之后下一段会被忘掉"),
        check_case("超出窗口的部分", [("insert", 8, b"ijklmn", False)], b"", False, 2,
                   why="容量 10：只留下标 8、9，其他的丢弃"),
        check_case("最后一段先到，前面有洞", [("insert", 2, b"c", True)], b"", False, 1,
                   why="知道总长度了，但不能关闭：字节还没写完"),
        check_case("最后一段完全放不下", [("insert", 20, b"z", True), ("insert", 0, b"ab", False)], b"ab", False, 0,
                   why="字节放不下，但总长度必须记住"),
        check_case("空片段结束一条流", [("insert", 0, b"ab", False), ("insert", 2, b"", True)], b"ab", True, 0,
                   why="空片段也能携带结束信息"),
        check_case("空流", [("insert", 0, b"", True)], b"", True, 0, why="长度为 0 的流也要能正常结束"),
        check_case("结束标记重复", [("insert", 0, b"ab", True), ("insert", 0, b"ab", True)], b"ab", True, 0,
                   why="重传的最后一段不能出错"),
        check_case("容量为 1，一个一个来", [("insert", 0, b"abc", False), ("read", 1), ("insert", 1, b"bc", False), ("read", 1),
                                         ("insert", 2, b"c", True)], b"abc", True, 0, capacity=1, why="最小的容量也要能工作"),
    ]
    print_table(["情况", "结果", "为什么"], cases, align=["<", "<", "<"])
    return len(cases)


def part_c_memory_bound():
    """
    不管片段怎样到达，字节流 + 重组器合起来不超过容量。

    【返回】观察到的最大占用
    """
    print_header("Part C · 内存上限：发送方再怎么发，也撑不爆接收方")
    capacity = 1000
    stream = BoundedByteStream(capacity)
    r = IntervalReassembler(stream)
    max_used = 0
    # 一个"恶意的"发送方：不断发窗口之内和之外的片段，永远不填上第 0 个字节
    for k in range(0, 1_000_000, 7):
        r.insert(1 + k % 5000, bytes(3), False)
        max_used = max(max_used, stream.buffered + r.pending_bytes)
    print(f"  发送方发了 {1_000_000 // 7:,} 个片段，分布在下标 1～5000，永远不发第 0 个字节。")
    print(f"  字节流 + 重组器的最大占用：{max_used} 字节，容量 {capacity} 字节。")
    print("  窗口右边界 = next_index + 字节流的剩余容量。暂存的字节都在窗口之内，所以两者之和不超过容量。")
    print("  代价：窗口外的字节被丢弃了，发送方要重发。这是用重传换内存。")
    return max_used


def main():
    """依次运行各部分，打印结论。"""
    ok = part_a_trace()
    n = part_b_edge_cases()
    max_used = part_c_memory_bound()
    print_header("结论")
    observations([
        f"乱序、重复、重叠、部分超出容量的片段，最后拼回了原文：{ok}。",
        f"{n} 个边界情况全部符合预期。它们大多来自同一个规律：先裁剪到窗口，再存，再把连续的部分写出去。",
        f"窗口保证了内存上限：恶意的发送方也只能占用 {max_used} 字节。",
    ])


if __name__ == "__main__":
    main()
