"""
=============================================================================
Stanford CS144 · 第 8 讲共享模块：hopsim.py —— 一条多跳路径上的分组
=============================================================================

【这个模块做什么】
    前七讲把网络画成一朵云。这里打开它：一条路径是一串链路，每条链路有速率和传播时延，
    路径上的交换机存储转发。这个模块用第 1 讲 netsim.py 的 Link 把它们串起来，并且记录每个分组
    在每一跳什么时候开始发送、什么时候发完、什么时候到达，这样可以和公式逐项核对。

【三种时延】
    传播时延（propagation）  比特在导线里走的时间 = 长度 / 信号速度。和分组大小无关。
    串行化时延（serialization） 把分组的所有比特推上线的时间 = 分组比特数 / 链路速率。和距离无关。
    排队时延（queueing）     前面的分组还没发完，要等。只有它是随机的。

【接口】
    hops = [Hop(rate_bps=1e9, prop_delay=0.005), Hop(rate_bps=100e6, prop_delay=0.001)]
    path = StoreForwardPath(sim, hops, on_deliver=fn)
    path.send(size_bytes, tag)        发一个分组；到达终点时调用 on_deliver(record)
    formula_delay(size_bytes, hops)   公式：Σ(p/r + l/c)
    cut_through_delay(size_bytes, header_bytes, hops)  直通交换的公式

【运行方式】
    python3 hopsim.py      # 运行自检（瞬间完成）
"""

from dataclasses import dataclass, field

import course_path
course_path.use("lecture01")

from netsim import Link, Simulator

SPEED_IN_FIBER = 2e8     # 光纤和铜缆里信号的速度，约 2/3 光速（米/秒）


@dataclass
class Hop:
    """
    一条链路。

    【字段】rate_bps：速率（比特/秒）；prop_delay：传播时延（秒）；queue_bytes：链路入口的缓冲区（None 为无限）；name：名字
    """
    rate_bps: float
    prop_delay: float
    queue_bytes: float = None
    name: str = ""

    def serialization(self, size_bytes):
        """串行化时延。【参数】size_bytes：分组字节数。【返回】秒。"""
        return 8.0 * size_bytes / self.rate_bps


def prop_from_km(km):
    """
    由长度算传播时延。

    【参数】km：千米
    【返回】秒
    """
    return km * 1000.0 / SPEED_IN_FIBER


def formula_delay(size_bytes, hops):
    """
    存储转发、没有排队时的端到端时延：t = Σ(p/r_i + l_i/c)。

    【参数】size_bytes：分组字节数；hops：Hop 列表
    【返回】秒（从第一个比特发出到最后一个比特到达）
    """
    total = 0.0
    for hop in hops:
        total += hop.serialization(size_bytes) + hop.prop_delay
    return total


def cut_through_delay(size_bytes, header_bytes, hops):
    """
    直通交换（cut-through）、没有排队时的端到端时延。

    【思路】交换机不等整个分组收完，只要读到头部（知道该往哪里发）就开始转发。
        所以中间每一跳只多花"收头部"的时间，整个分组只串行化一次（按最慢的链路算）。
        只有当输出链路不比输入链路慢时才能这样做，否则比特会堆积，还是要存储。
    【参数】size_bytes；header_bytes：交换机要读多少字节才能决定转发；hops：Hop 列表
    【返回】秒
    【边界】路径上出现"先快后慢"时抛 ValueError：那种情况实际上要退回存储转发。
    """
    rates = [hop.rate_bps for hop in hops]
    if any(rates[i + 1] < rates[i] for i in range(len(rates) - 1)):
        raise ValueError("下一跳比上一跳慢时不能直通：比特会堆积")
    total = 0.0
    for i, hop in enumerate(hops):
        total += hop.prop_delay
        if i < len(hops) - 1:
            total += hop.serialization(header_bytes)
    return total + 8.0 * size_bytes / min(rates)


@dataclass
class PacketRecord:
    """
    一个分组走过路径的记录。

    【字段】tag：标签；size：字节数；sent_at：交给第一跳的时刻；delivered_at：最后一个比特到达终点的时刻；
        hop_times：每一跳的 (开始串行化, 串行化结束)；
    """
    tag: object
    size: float
    sent_at: float
    delivered_at: float = None
    hop_times: list = field(default_factory=list)


class StoreForwardPath:
    """
    一条存储转发的路径：每一跳都要收完整个分组才开始往下一跳发。

    【思路】每一跳一条 Link。Link 到达时（最后一个比特到了）把分组交给下一跳的 Link。
    【字段】links：Link 列表；records：所有分组的记录；dropped：被丢弃的分组数
    【边界】某一跳队列满了就丢弃，dropped 加一，on_deliver 不会被调用。
    """

    def __init__(self, sim, hops, on_deliver=None):
        """
        【参数】sim：Simulator；hops：Hop 列表；on_deliver：函数 on_deliver(record)
        """
        self.sim = sim
        self.hops = hops
        self.on_deliver = on_deliver
        self.records = []
        self.dropped = 0
        self.links = []
        for i, hop in enumerate(hops):
            link = Link(sim, hop.rate_bps, hop.prop_delay, hop.queue_bytes,
                        on_arrive=lambda pkt, i=i: self._arrive(pkt, i), name=hop.name or f"hop{i}")
            self.links.append(link)

    def send(self, size_bytes, tag=None):
        """
        发一个分组。

        【参数】size_bytes：字节数；tag：任意标签
        【返回】PacketRecord
        """
        record = PacketRecord(tag, size_bytes, self.sim.now)
        self.records.append(record)
        self._enter(record, 0)
        return record

    def _enter(self, record, index):
        """
        分组进入第 index 跳。

        【参数】record；index：第几跳
        【思路】开始串行化的时刻 = max(现在, 发送器空闲时刻)。这个差值就是排队时延。
        """
        link = self.links[index]
        start = max(self.sim.now, link._free_at)
        accepted = link.send(record.size, record)
        if not accepted:
            self.dropped += 1
            return
        record.hop_times.append((start, link._free_at))

    def _arrive(self, record, index):
        """分组（最后一个比特）到达第 index 跳的末端。【参数】record；index。"""
        if index + 1 < len(self.links):
            self._enter(record, index + 1)
        else:
            record.delivered_at = self.sim.now
            if self.on_deliver is not None:
                self.on_deliver(record)


def _self_test():
    """基本自检。"""
    hops = [Hop(1e6, 0.001), Hop(2e6, 0.002), Hop(1e6, 0.003), Hop(4e6, 0.001)]
    size = 1250      # 1250 字节 = 10000 比特

    # ---- 1. 公式 ----
    expected = 0.01 + 0.001 + 0.005 + 0.002 + 0.01 + 0.003 + 0.0025 + 0.001
    assert abs(formula_delay(size, hops) - expected) < 1e-12

    # ---- 2. 模拟和公式一致 ----
    sim = Simulator()
    done = []
    path = StoreForwardPath(sim, hops, on_deliver=done.append)
    path.send(size, "a")
    sim.run()
    assert abs(done[0].delivered_at - expected) < 1e-12
    assert len(done[0].hop_times) == 4

    # ---- 3. 排队：第二个分组紧跟着发，在第一跳就要等 ----
    sim = Simulator()
    done = []
    path = StoreForwardPath(sim, [Hop(1e6, 0.0)], on_deliver=done.append)
    path.send(size, "a")
    path.send(size, "b")
    sim.run()
    assert abs(done[1].delivered_at - 0.02) < 1e-12

    # ---- 4. 队列满了丢弃 ----
    sim = Simulator()
    path = StoreForwardPath(sim, [Hop(1e6, 0.0, queue_bytes=2000)])
    path.send(1500)
    path.send(1500)
    assert path.dropped == 1

    # ---- 5. 直通：速率相同时只串行化一次 ----
    same = [Hop(1e6, 0.001), Hop(1e6, 0.001)]
    assert abs(cut_through_delay(1250, 14, same) - (0.002 + 14 * 8 / 1e6 + 0.01)) < 1e-12

    print("hopsim.py 自检通过：公式、模拟和公式一致、排队、丢弃、直通。")


if __name__ == "__main__":
    _self_test()
