"""
=============================================================================
Stanford CS144 · 第 8 讲 · 05_real_delay.py —— 把一条真实路径的时延分解开
=============================================================================

【这个脚本要回答的问题】（讲义 §7）
    ping 只给你一个数字。能不能把它分解成传播和串行化？能不能估计路径的速率？

【方法】（Van Jacobson 1997 年的 pathchar 的思路）
    排队时延只会让时延变大，所以同样的大小多测几次，取**最小值**，就基本去掉了排队。
    最小 RTT 是分组大小的线性函数：

        RTT_min(s) = 截距 + 斜率 × s

        截距：和大小无关的部分（传播 + 处理）。
        斜率：每多一个字节要多花的时间 = 来回各走一遍每条链路的串行化 = 2 × Σ(8 / r_i)。

    用不同的大小各测很多次，拟合一条直线，就得到了两者。

【两部分】
    A：在模拟网络上验证方法（答案已知）。
    B：--internet：在真实的路径上测（默认不运行）。

【运行方式】
    python3 05_real_delay.py                 # 瞬间完成，只有模拟部分，结果每次相同
    python3 05_real_delay.py --internet      # 约 1 分钟，对 cs144.keithw.org 发真实的 ping（每 0.2 秒最多一个）

【使用边界】
    这是测量工具，不要用来高频探测别人的机器。这里遵守原课 Checkpoint 4 的建议：不比每 0.2 秒一个更快。
"""

import argparse
import math
import random
import socket
import time

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

from console import print_header, print_table, observations, si_rate, si_time
from hopsim import Hop, StoreForwardPath, prop_from_km
from icmp_tools import open_icmp_socket, probe
from netsim import Simulator

SIZES = (64, 200, 400, 600, 800, 1000, 1200, 1400)
HEADERS = 28            # IP 20 + ICMP 8


def fit_line(xs, ys):
    """
    最小二乘拟合直线 y = a + b x。

    【参数】xs、ys：等长的列表
    【返回】(a, b, r2)；r2 是拟合优度（1 表示完全在直线上）
    【边界】点数少于 2 或 x 全部相同时抛 ValueError。
    【Python 小知识】math.fsum 比 sum 更精确，而且不同版本的 Python 结果相同（3.12 之后 sum 改成了补偿求和）。
    """
    n = len(xs)
    if n < 2:
        raise ValueError("至少要两个点")
    mx = math.fsum(xs) / n
    my = math.fsum(ys) / n
    sxx = math.fsum((x - mx) ** 2 for x in xs)
    if sxx == 0:
        raise ValueError("x 全部相同，无法拟合")
    sxy = math.fsum((x - mx) * (y - my) for x, y in zip(xs, ys))
    b = sxy / sxx
    a = my - b * mx
    ss_res = math.fsum((y - a - b * x) ** 2 for x, y in zip(xs, ys))
    ss_tot = math.fsum((y - my) ** 2 for y in ys)
    r2 = 1.0 - ss_res / ss_tot if ss_tot > 0 else 1.0
    return a, b, r2


def simulated_rtt(hops, size, cross_rng=None, cross_load=0.0):
    """
    在模拟网络上测一次 RTT（来回各走一遍路径），排队时延用随机数近似。

    【参数】hops：Hop 列表；size：分组字节数；cross_rng：随机数生成器；cross_load：排队的强度（平均排队时延，秒）
    【返回】RTT（秒）
    【思路】一次 RTT = 正向路径的时延 + 反向路径的时延（回复和请求一样大）。
        其他流量造成的排队用指数分布近似，这样不必模拟所有流量，模拟器只负责把时延公式走一遍。
    """
    total = 0.0
    for _direction in range(2):
        s = Simulator()
        done = []
        path = StoreForwardPath(s, hops, on_deliver=done.append)
        path.send(size)
        s.run()
        total += done[0].delivered_at
    if cross_rng is not None and cross_load > 0:
        total += cross_rng.expovariate(1 / cross_load)
    return total


def part_a_simulated():
    """
    模拟网络上验证方法。

    【返回】dict：真实值和估计值
    """
    hops = [Hop(100e6, prop_from_km(5), name="100 Mbit/s"), Hop(1e9, prop_from_km(500), name="1 Gbit/s"), Hop(10e9, prop_from_km(4000), name="10 Gbit/s"), Hop(50e6, prop_from_km(20), name="50 Mbit/s")]
    print_header("Part A · 在模拟网络上验证方法（答案已知）：4 跳，排队时延平均 3 ms（指数分布）")
    print_table(["链路", "传播时延"], [[h.name, si_time(h.prop_delay)] for h in hops])
    rng = random.Random(8)
    true_slope = 2 * sum(8 / h.rate_bps for h in hops)
    true_intercept = 2 * sum(h.prop_delay for h in hops)
    rows = []
    out = {}
    for probes in (1, 5, 20, 100, 500):
        xs = []
        ys = []
        for size in SIZES:
            samples = [simulated_rtt(hops, size, rng, 0.003) for _ in range(probes)]
            xs.append(size)
            ys.append(min(samples))
        a, b, r2 = fit_line(xs, ys)
        effective = 2 * 8 / b if b > 0 else float("inf")
        out[probes] = (a, b, r2)
        rows.append([probes, si_time(a), f"{b * 1e6:.3f}", si_rate(effective), f"{r2:.4f}"])
    rows.append(["真实值", si_time(true_intercept), f"{true_slope * 1e6:.3f}", si_rate(2 * 8 / true_slope), "—"])
    print()
    print_table(["每种大小测几次", "截距（传播）", "斜率（µs/字节）", "等效速率", "拟合优度 r²"], rows)
    print("\n  等效速率的定义：1 / Σ(1/r_i)。它比最慢的链路还慢一点，因为每条链路都要串行化一次。这里最慢的是 50 Mbit/s。")
    print("  只测一次时，排队的噪声淹没了信号。测得越多，最小值越接近没有排队的情况。这就是'取最小值'的理由。")
    return dict(out=out, true_slope=true_slope, true_intercept=true_intercept)


def part_b_real(target):
    """
    真实的路径。

    【参数】target：主机名
    【返回】dict：拟合结果；不能测量时返回 None
    """
    print_header(f"Part B · 真实的路径（目标 {target}，只隐去 IP 地址）")
    sock = open_icmp_socket()
    if sock is None:
        print("  这个系统不允许普通用户打开 ICMP 套接字，跳过。")
        return None
    try:
        ip = socket.gethostbyname(target)
    except OSError as error:
        print(f"  解析不了 {target}：{error}")
        return None
    per_size = 20
    xs = []
    ys = []
    rows = []
    sequence = 0
    for size in SIZES:
        payload = b"x" * (size - HEADERS)
        samples = []
        for _ in range(per_size):
            sequence += 1
            result = probe(sock, ip, sequence, payload=payload, timeout=1.0)
            if result["kind"] == "reply":
                samples.append(result["rtt"])
            time.sleep(0.2)
        if samples:
            xs.append(size)
            ys.append(min(samples))
            median = sorted(samples)[len(samples) // 2]
            rows.append([size, len(samples), si_time(min(samples)), si_time(median), si_time(max(samples))])
    sock.close()
    if len(xs) < 2:
        print("  收到的回复太少，无法拟合。")
        return None
    print_table(["大小（字节，含 IP 和 ICMP 头部）", "收到几个回复", "最小 RTT", "中位数", "最大"], rows)
    a, b, r2 = fit_line(xs, ys)
    print(f"\n  拟合：RTT_min = {a * 1000:.2f} ms + {b * 1e6:.3f} µs/字节 × 大小，r² = {r2:.3f}。")
    if b > 0 and r2 > 0.5:
        print(f"  等效速率 2×8/斜率 = {si_rate(2 * 8 / b)}（这是 1/Σ(1/r_i)，比最慢的链路还低一点，也可能被其他因素影响）。")
    else:
        print(f"  r² 很低，说明这些点基本不在一条斜线上，斜率不可信。不要用它推算速率。")
        print(f"  这本身是一个结果：1400 字节比 64 字节的 RTT 只多 {(ys[-1] - ys[0]) * 1000:.2f} ms，比测量的波动还小。")
        print("  这条路径的时延几乎全是传播，串行化小到这种方法测不出来。")
    print("  真实路径上还有 ICMP 的特殊处理、链路层的聚合和压缩，这个结果只是一个粗略的估计。")
    return dict(intercept=a, slope=b, r2=r2)


def main():
    """解析参数，运行各部分，打印结论。"""
    parser = argparse.ArgumentParser(description="把一条真实路径的时延分解开")
    parser.add_argument("--internet", action="store_true", help="在真实的路径上测量")
    parser.add_argument("--target", default="cs144.keithw.org", help="探测的目标")
    args = parser.parse_args()

    a = part_a_simulated()
    b = part_b_real(args.target) if args.internet else None

    print_header("结论")
    estimates = a["out"]
    lines = [
        f"模拟网络的真实斜率 {a['true_slope'] * 1e6:.3f} µs/字节，每种大小测 500 次时估计 {estimates[500][1] * 1e6:.3f}；只测 1 次时 {estimates[1][1] * 1e6:.3f}。",
        f"截距（传播）的真实值 {si_time(a['true_intercept'])}，测 500 次时估计 {si_time(estimates[500][0])}。",
        "排队时延只增不减，所以取最小值可以去掉它。这个技巧第 9 讲的测量和第 11 讲的 BBR 都会用到。",
    ]
    if b:
        lines.append(f"真实的路径：截距 {si_time(b['intercept'])}，斜率 {b['slope'] * 1e6:.3f} µs/字节，r² = {b['r2']:.3f}。这只是这条路径这一次的结果。")
    elif args.internet:
        lines.append("这次没有得到真实路径的结果，见上面的说明。")
    else:
        lines.append("加上 --internet 可以在真实的路径上测量。")
    observations(lines)


if __name__ == "__main__":
    main()
