"""
noc.py -- a cycle-level mesh network-on-chip: routers with input buffers, credit-based flow control, XY / west-first /
fully adaptive routing, traffic generators, latency-throughput measurement, and slow chiplet-boundary links
====================================================================================================================

[Why we need it]
    The PE arrays, vector units and buffer banks of an accelerator talk through an on-chip network (NoC). A
    k x k MESH is the default topology: each router connects to its four neighbours and one local unit, all wires
    are short, and the network grows with the chip. What the designer must know is how LATENCY grows with LOAD:
    near-zero load a packet needs (hops x per-hop delay) + its serialization; as load rises, packets queue in
    router buffers, and at the SATURATION throughput the latency explodes. This module simulates such a network
    packet by packet, cycle by cycle, so those curves -- and the effects of traffic patterns, buffer sizes, routing
    algorithms and slow chiplet-to-chiplet links -- can be measured rather than assumed.

[The router] (one per mesh node)
    - Five ports: N, E, S, W and L (local: injection from / ejection to the attached unit).
    - Each input port has a FIFO buffer of `buffer_flits` flits. A packet of `size` flits moves as a unit with
      VIRTUAL CUT-THROUGH flow control: it may leave for the next router only if that router's input buffer has
      room for the WHOLE packet. Room is tracked with CREDITS: the sender knows how many free flits the receiver
      has; credits are spent when a packet is sent and returned when its tail leaves the receiver's buffer.
    - Each cycle, every free output port picks one requesting input (round-robin) among the input buffers whose
      HEAD packet is ready and wants that output. A granted packet occupies the output link and its input port for
      `size` cycles (one flit per cycle), reaches the next router after `link_delay`, and may leave it after a
      further `router_delay` (route computation + allocation).
    - Routing: "xy" (dimension order: first X, then Y -- deterministic, deadlock-free on a mesh), "west_first"
      (turn model: go west first if needed, then adaptively -- deadlock-free and partially adaptive), "adaptive"
      (any productive direction, the one with most credits -- deadlocks are possible with one buffer per port).

[Usage]
    import noc
    cfg = noc.NoCConfig(k=8)
    res = noc.simulate(cfg, noc.uniform(cfg), rate=0.2, size=4)
    res.latency, res.throughput
    makespan, pkts = noc.run_trace(cfg, [(0, 0, 63, 8), (0, 5, 63, 8)])    # an exact list of packets

[Edge cases]
    - Rates are offered loads in flits per node per cycle; a node creates a packet with probability rate / size
      each cycle (Bernoulli). Source queues are unbounded: above saturation they grow, and latency grows with the
      run length (we report the measured window).
    - A run declares DEADLOCK if packets are in the network but none moves for `stall_limit` cycles.
"""

import random
from collections import deque
from dataclasses import dataclass, field

PORTS = ("N", "E", "S", "W", "L")
OPP = {"N": "S", "S": "N", "E": "W", "W": "E"}
STEP = {"N": (0, -1), "S": (0, 1), "E": (1, 0), "W": (-1, 0)}


@dataclass(frozen=True)
class NoCConfig:
    """
    Network parameters.

    [Fields]
        k                 : the mesh is k x k routers (node id = y * k + x)
        buffer_flits      : input buffer depth per port, in flits (>= the largest packet)
        router_delay      : cycles from a head's arrival until it may leave (routing + allocation)
        link_delay        : cycles on a wire between routers
        routing           : "xy", "west_first" or "adaptive"
        chiplet           : if > 0, the mesh is cut into chiplets of chiplet x chiplet routers; links that cross a
                            chiplet boundary (through an interposer or package substrate) are slower
        boundary_delay    : extra latency of a boundary link
        boundary_slowdown : cycles per flit on a boundary link (2 = half the bandwidth)
        stall_limit       : cycles without progress that count as a deadlock
    """
    k: int = 8
    buffer_flits: int = 8
    router_delay: int = 1
    link_delay: int = 1
    routing: str = "xy"
    chiplet: int = 0
    boundary_delay: int = 0
    boundary_slowdown: int = 1
    stall_limit: int = 2000

    @property
    def nodes(self):
        return self.k * self.k

    def xy(self, node):
        return node % self.k, node // self.k

    def neighbor(self, node, port):
        """Node reached through an output port, or None at the mesh edge."""
        x, y = self.xy(node)
        dx, dy = STEP[port]
        nx, ny = x + dx, y + dy
        if 0 <= nx < self.k and 0 <= ny < self.k:
            return ny * self.k + nx
        return None

    def is_boundary(self, a, b):
        """True if the link between nodes a and b crosses a chiplet boundary."""
        if not self.chiplet:
            return False
        (ax, ay), (bx, by) = self.xy(a), self.xy(b)
        return ax // self.chiplet != bx // self.chiplet or ay // self.chiplet != by // self.chiplet


@dataclass
class Packet:
    """One packet: source, destination, size in flits, and its timestamps (cycles)."""
    pid: int
    src: int
    dst: int
    size: int
    t_create: int
    ready: int = 0          # cycle from which its head may leave the buffer it is in
    t_done: int = -1        # cycle its tail was ejected
    hops: int = 0


@dataclass
class NoCResult:
    """
    Outcome of a run.

    [Fields] latency (mean cycles from creation to tail ejection, measured packets), throughput (accepted flits per
        node per cycle in the measurement window), offered (flits per node per cycle), delivered (measured packets
        delivered), measured (measured packets created), mean_hops, deadlock (bool), zero_load (mean hops x per-hop
        delay + size, the latency an empty network would give)
    """
    latency: float
    throughput: float
    offered: float
    delivered: int
    measured: int
    mean_hops: float
    deadlock: bool
    zero_load: float
    latencies: list = field(default_factory=list)


# =====================================================================================================================
# Routing
# =====================================================================================================================

def productive(cfg, node, dst):
    """Output ports that move a packet closer to dst (empty list when node == dst)."""
    (x, y), (dx, dy) = cfg.xy(node), cfg.xy(dst)
    out = []
    if dx > x:
        out.append("E")
    if dx < x:
        out.append("W")
    if dy > y:
        out.append("S")
    if dy < y:
        out.append("N")
    return out


def route_options(cfg, node, dst):
    """
    Allowed output ports for a packet at `node` heading to `dst`, by the configured routing algorithm.

    [Idea]
        xy         : X first, then Y -- a single port. Packets never turn from Y back to X, so no cycle of buffer
                     dependences can form (dimension-order routing is deadlock-free on a mesh).
        west_first : if the destination is to the west, go west (only); otherwise any productive port among
                     E, N, S. Forbidding the two turns INTO west breaks every cycle (Glass & Ni's turn model).
        adaptive   : any productive port -- maximum path diversity, but cycles of waiting packets can form.
    """
    if node == dst:
        return ["L"]
    prod = productive(cfg, node, dst)
    if cfg.routing == "xy":
        return [p for p in prod if p in ("E", "W")][:1] or prod[:1]
    if cfg.routing == "west_first":
        return ["W"] if "W" in prod else prod
    if cfg.routing == "adaptive":
        return prod
    raise ValueError(f"unknown routing {cfg.routing!r}")


# =====================================================================================================================
# Traffic patterns: functions (rng, src) -> dst
# =====================================================================================================================

def uniform(cfg):
    """Uniform random: every other node equally likely."""
    def dst(rng, s):
        d = rng.randrange(cfg.nodes - 1)
        return d + (d >= s)
    return dst


def transpose(cfg):
    """Transpose: (x, y) -> (y, x). Diagonal nodes send nothing (they would send to themselves)."""
    def dst(rng, s):
        x, y = cfg.xy(s)
        return x * cfg.k + y
    return dst


def hotspot(cfg, fraction=0.2, spot=None):
    """A fraction of the traffic goes to one node (e.g. a buffer bank everybody reads); the rest is uniform."""
    spot = cfg.nodes // 2 + cfg.k // 2 if spot is None else spot
    uni = uniform(cfg)

    def dst(rng, s):
        if s != spot and rng.random() < fraction:
            return spot
        return uni(rng, s)
    return dst


def neighbor(cfg):
    """Nearest neighbour to the east (wrapping to the row's first node): one hop for almost everyone."""
    def dst(rng, s):
        x, y = cfg.xy(s)
        return y * cfg.k + (x + 1) % cfg.k
    return dst


# =====================================================================================================================
# The simulator
# =====================================================================================================================

class Network:
    """
    The state of a mesh network, advanced one cycle at a time by step().

    [Idea] Separating the network from the traffic lets the same router model serve two uses: random traffic for
        latency-throughput curves (simulate) and exact packet traces of an accelerator's data movement
        (run_trace, used by toy_accel.py).
    [Attributes] buf (input buffers), credits (free flits downstream of every output), out_busy / in_busy (cycle
        until which a port is transmitting), rr (round-robin pointers), srcq (unbounded source queues),
        events (cycle -> credit returns), in_network (packets injected and not yet ejected), delivered (list)
    """

    def __init__(self, cfg):
        self.cfg = cfg
        N = cfg.nodes
        self.buf = [{p: deque() for p in PORTS} for _ in range(N)]
        self.credits = [{p: cfg.buffer_flits for p in PORTS} for _ in range(N)]
        self.out_busy = [{p: 0 for p in PORTS} for _ in range(N)]
        self.in_busy = [{p: 0 for p in PORTS} for _ in range(N)]
        self.rr = [{p: 0 for p in PORTS} for _ in range(N)]
        self.srcq = [deque() for _ in range(N)]
        self.events = {}
        self.in_network = 0
        self.delivered = []

    def offer(self, pk):
        """Put a packet in its source's queue (it enters the network when the local input buffer has room)."""
        self.srcq[pk.src].append(pk)

    def busy(self):
        """True while any packet is queued or in flight."""
        return self.in_network > 0 or any(self.srcq)

    def step(self, t):
        """
        Advance one cycle: credit returns, injection (one packet per node), then switch allocation and traversal at
        every router. Returns True if any packet moved (used for deadlock detection).
        """
        cfg = self.cfg
        buf, credits, out_busy, in_busy, rr = self.buf, self.credits, self.out_busy, self.in_busy, self.rr
        for node, port, flits in self.events.pop(t, ()):
            credits[node][port] += flits
        for s in range(cfg.nodes):
            q = self.srcq[s]
            if q and credits[s]["L"] >= q[0].size:
                pk = q.popleft()
                credits[s]["L"] -= pk.size
                pk.ready = t + cfg.router_delay
                buf[s]["L"].append(pk)
                self.in_network += 1
        moved = False
        n = len(PORTS)
        for r in range(cfg.nodes):
            for out in PORTS:
                if out_busy[r][out] > t:
                    continue
                cands = []
                for i, inp in enumerate(PORTS):
                    q = buf[r][inp]
                    if not q or in_busy[r][inp] > t:
                        continue
                    pk = q[0]
                    if pk.ready > t:
                        continue
                    opts = route_options(cfg, r, pk.dst)
                    if out not in opts:
                        continue
                    if len(opts) > 1:                              # adaptive: take the port with the most credits
                        best = max(opts, key=lambda o: (credits[r][o], -PORTS.index(o)))
                        if best != out and credits[r][best] >= pk.size and out_busy[r][best] <= t:
                            continue
                    if out != "L" and credits[r][out] < pk.size:
                        continue
                    cands.append(i)
                if not cands:
                    continue
                win = min(cands, key=lambda i: (i - rr[r][out]) % n)
                rr[r][out] = (win + 1) % n
                inp = PORTS[win]
                pk = buf[r][inp].popleft()
                if out == "L":
                    slow = 1
                    pk.t_done = t + pk.size
                    self.in_network -= 1
                    self.delivered.append(pk)
                else:
                    d = cfg.neighbor(r, out)
                    boundary = cfg.is_boundary(r, d)
                    slow = cfg.boundary_slowdown if boundary else 1
                    delay = cfg.link_delay + (cfg.boundary_delay if boundary else 0)
                    credits[r][out] -= pk.size
                    pk.ready = t + delay + cfg.router_delay
                    pk.hops += 1
                    buf[d][OPP[out]].append(pk)
                busy = pk.size * slow
                out_busy[r][out] = t + busy
                in_busy[r][inp] = t + busy
                # the tail leaves this input buffer after `busy` cycles: return the credits to whoever feeds it
                if inp == "L":
                    self.events.setdefault(t + busy, []).append((r, "L", pk.size))
                else:
                    up = cfg.neighbor(r, inp)
                    self.events.setdefault(t + busy + 1, []).append((up, OPP[inp], pk.size))
                moved = True
        return moved


def simulate(cfg, pattern, rate, size=4, warmup=300, measure=1000, drain=3000, seed=0, sources=None):
    """
    Run the network with Bernoulli traffic and measure latency and accepted throughput.

    [Args]
        cfg      : NoCConfig
        pattern  : function (rng, src) -> dst (uniform, transpose, hotspot, neighbor, or your own)
        rate     : offered load, flits per node per cycle
        size     : flits per packet
        warmup, measure : packets created in [warmup, warmup + measure) are MEASURED; earlier ones warm the
                   network up
        drain    : extra cycles allowed for measured packets to arrive
        seed     : random seed (Python's random.Random)
        sources  : optional list of nodes that inject (default: all)
    [Returns] NoCResult
    [Edge cases] Packets whose source equals their destination are skipped. If a deadlock is detected the run
        stops and NoCResult.deadlock is True (latency then covers only delivered packets). Accepted throughput
        counts the flits ejected during the measurement window.
    """
    if size > cfg.buffer_flits:
        raise ValueError("packets must fit in an input buffer (virtual cut-through)")
    rng = random.Random(seed)
    net = Network(cfg)
    sources = list(range(cfg.nodes)) if sources is None else sources
    t_end_create = warmup + measure
    measured = []
    pid = 0
    p_new = rate / size
    last_progress = 0
    deadlock = False
    seen = 0
    ejected_flits = 0
    t = 0
    while True:
        if t < t_end_create:
            for s in sources:
                if rng.random() < p_new:
                    d = pattern(rng, s)
                    if d == s:
                        continue
                    pk = Packet(pid, s, d, size, t)
                    pid += 1
                    net.offer(pk)
                    if t >= warmup:
                        measured.append(pk)
        if net.step(t):
            last_progress = t
        if warmup <= t < t_end_create:
            ejected_flits += sum(p.size for p in net.delivered[seen:])
        seen = len(net.delivered)
        t += 1
        if t >= t_end_create and all(p.t_done >= 0 for p in measured):
            break
        if t > t_end_create + drain:
            break
        if net.in_network and t - last_progress > cfg.stall_limit:
            deadlock = True
            break
    done = [p for p in measured if p.t_done >= 0]
    lat = [p.t_done - p.t_create for p in done]
    hops = [p.hops for p in done]
    mean_hops = sum(hops) / len(hops) if hops else 0.0
    zl = mean_hops * (cfg.link_delay + cfg.router_delay) + cfg.router_delay + size
    return NoCResult(sum(lat) / len(lat) if lat else float("inf"), ejected_flits / (measure * cfg.nodes), rate,
                     len(done), len(measured), mean_hops, deadlock, zl, lat)


def run_trace(cfg, packets, max_cycles=10_000_000):
    """
    Replay an exact list of packets through the network.

    [Args] packets: iterable of (t_release, src, dst, size) -- a packet is offered to its source at t_release
    [Returns] (makespan: cycle the last tail was ejected, list of Packet with t_done filled in)
    [Edge cases] Packets with src == dst are delivered at once (local transfer, no network). Raises RuntimeError on
        deadlock or if max_cycles is exceeded.
    """
    pend = sorted((int(t), s, d, z) for t, s, d, z in packets)
    net = Network(cfg)
    pkts = []
    i = 0
    t = 0
    last = 0
    makespan = 0
    while i < len(pend) or net.busy():
        while i < len(pend) and pend[i][0] <= t:
            t0, s, d, z = pend[i]
            pk = Packet(i, s, d, z, t0)
            if s == d:
                pk.t_done = t0
                makespan = max(makespan, t0)
            else:
                net.offer(pk)
            pkts.append(pk)
            i += 1
        if net.step(t):
            last = t
        t += 1
        if t > max_cycles:
            raise RuntimeError("trace did not finish")
        if net.in_network and t - last > cfg.stall_limit:
            raise RuntimeError("deadlock while replaying the trace")
    makespan = max([makespan] + [p.t_done for p in pkts])
    return makespan, pkts


def saturation(cfg, pattern, size=4, lo=0.02, hi=1.0, steps=7, factor=3.0, **kw):
    """
    Saturation throughput by bisection: the highest offered load whose mean latency stays below
    `factor` x the zero-load latency (and that delivers everything).

    [Returns] (rate, NoCResult at that rate)
    """
    base = simulate(cfg, pattern, lo, size, **kw)
    limit = factor * base.latency
    best = (lo, base)
    for _ in range(steps):
        mid = (lo + hi) / 2
        r = simulate(cfg, pattern, mid, size, **kw)
        if not r.deadlock and r.delivered == r.measured and r.latency <= limit:
            lo, best = mid, (mid, r)
        else:
            hi = mid
    return best


# =====================================================================================================================
# Self-test
# =====================================================================================================================

if __name__ == "__main__":
    cfg = NoCConfig(k=4)
    # zero load: latency = hops x (link + router) + router + size
    r = simulate(cfg, uniform(cfg), 0.01, 4, warmup=100, measure=600)
    assert r.delivered == r.measured and abs(r.latency - r.zero_load) < 1.0, (r.latency, r.zero_load)
    # XY routing: packets take minimal paths
    one = simulate(NoCConfig(k=4), lambda rng, s: 15, 0.02, 4, warmup=0, measure=300, sources=[0])
    assert one.mean_hops == 6 and one.delivered == one.measured
    # latency grows with load; throughput follows the offered load below saturation
    lo = simulate(NoCConfig(k=6), uniform(NoCConfig(k=6)), 0.05, 4)
    hi = simulate(NoCConfig(k=6), uniform(NoCConfig(k=6)), 0.30, 4)
    assert hi.latency > lo.latency and abs(lo.throughput - 0.05) < 0.02, (lo.latency, hi.latency, lo.throughput)
    # neighbour traffic saturates far later than uniform
    assert simulate(NoCConfig(k=6), neighbor(NoCConfig(k=6)), 0.6, 4).latency < 30
    # trace replay: two packets into the same node share its ejection port
    ms, pk = run_trace(NoCConfig(k=4), [(0, 0, 15, 8), (0, 3, 15, 8)])
    assert all(p.t_done > 0 for p in pk) and ms >= 16
    # slow chiplet boundaries raise latency
    ch = simulate(NoCConfig(k=6, chiplet=3, boundary_delay=4, boundary_slowdown=2), uniform(NoCConfig(k=6)), 0.05, 4)
    assert ch.latency > lo.latency
    print("noc.py self-test passed")
    print(f"  6x6 mesh, uniform, 4-flit packets: latency {lo.latency:.1f} cycles at 0.05 flits/node/cycle, "
          f"{hi.latency:.1f} at 0.30; zero-load {lo.zero_load:.1f}")
