"""
channels.py -- a cycle-level simulator of latency-insensitive hardware: ready/valid channels, FIFOs, back-pressure
=================================================================================================================

[Why we need it]
    Accelerator blocks (a PE, a vector unit, a global buffer, a NoC router) are designed separately and connected
    by CHANNELS. If every block had to know the exact cycle in which its inputs arrive, changing one block's
    latency would break all the others. LATENCY-INSENSITIVE design avoids that: data moves only when the sender
    says "I have data" (valid) AND the receiver says "I can take it" (ready); FIFOs between blocks absorb
    differences in timing; a full FIFO makes its sender wait (back-pressure). This is the style of the CS 217 labs
    (C++/SystemC blocks with MatchLib-style channels) and of almost every on-chip interface (AXI-Stream, ...).

    This module simulates such circuits cycle by cycle, so that the consequences can be measured:
    - how deep a FIFO must be to keep full throughput (registered "ready" needs depth 2, not 1);
    - how much buffering absorbs a bursty producer or consumer;
    - why paths that split and merge again (fork/join) need buffers matched to their latency difference;
    - that adding pipeline stages ("relay stations") changes latency but not results;
    - how an undersized FIFO deadlocks a design.

[Usage]
    from channels import Circuit
    c = Circuit()
    a, b = c.fifo("a", depth=2), c.fifo("b", depth=2)
    c.source("src", a, values=range(10))
    c.stage("mul2", a, b, fn=lambda v: 2 * v, latency=3)
    snk = c.sink("snk", b)
    result = c.run()
    print(result.cycles, snk.values())

[The timing model -- one clock cycle]
    1. At the start of the cycle every FIFO takes a snapshot of its occupancy (these are the REGISTERED signals).
    2. Components act in reverse order of creation (consumers before producers). A consumer pops if the FIFO was
       non-empty at the start of the cycle (an item pushed in this cycle is visible only from the next cycle).
       A producer pushes if the FIFO had room at the start of the cycle -- or, for a FIFO with comb_ready=True,
       also if its consumer popped in this same cycle (the "ready" signal then travels combinationally from the
       consumer back to the producer).
    3. Every push and pop is a handshake "fire" (valid and ready in the same cycle) and is recorded.
    Results never depend on the order in which components are evaluated, except through comb_ready, which is
    exactly the point: a combinational ready path makes a stage depend on what happens downstream in the same cycle.

[Edge cases]
    - Build circuits in data-flow order (sources first, sinks last) so that consumers are evaluated first; with
      comb_ready FIFOs in a feedback loop the result would depend on evaluation order (in hardware: a
      combinational loop), which this simulator does not support.
    - Deadlock is declared when nothing moves for `stall_limit` cycles while work remains.
"""

import random
from collections import deque


class Item:
    """A data item travelling through the circuit: its value, a serial number, and the cycle it was created."""
    __slots__ = ("value", "serial", "born")

    def __init__(self, value, serial, born):
        self.value, self.serial, self.born = value, serial, born


class Fifo:
    """
    A FIFO channel with ready/valid handshakes on both sides.

    [Args]
        name       : label
        depth      : capacity in items (>= 1)
        comb_ready : False (default) = "ready" is a registered signal: the producer sees "full" if the FIFO was full
                     at the start of the cycle, even if the consumer takes an item in the same cycle.
                     True = ready also depends combinationally on the consumer's pop in the same cycle (a "bypass" /
                     pass-through ready).
    [Signals recorded per cycle] valid_in/ready_in/fire_in on the producer side, valid_out/ready_out/fire_out on the
        consumer side, and the occupancy at the end of the cycle (see Circuit.run(trace=True)).
    [Edge cases] depth < 1 raises ValueError. Only one producer and one consumer per FIFO (as in hardware).
    """

    def __init__(self, name, depth=2, comb_ready=False):
        if depth < 1:
            raise ValueError("a FIFO needs depth >= 1")
        self.name, self.depth, self.comb_ready = name, depth, comb_ready
        self.items = deque()
        self.transfers = 0
        self.max_occupancy = 0
        self.full_cycles = 0
        self._begin()

    def _begin(self):
        """Start a new cycle: snapshot the occupancy and clear this cycle's handshake signals."""
        self._start = len(self.items)
        self._pops = 0
        self._pushes = 0
        self.sig = {"valid_in": False, "ready_in": False, "fire_in": False, "data_in": None,
                    "valid_out": False, "ready_out": False, "fire_out": False, "data_out": None}

    def _end(self):
        """End of cycle: update statistics."""
        self.max_occupancy = max(self.max_occupancy, len(self.items))
        if len(self.items) >= self.depth:
            self.full_cycles += 1

    # ---- consumer side -------------------------------------------------------------------------------------------

    def valid(self):
        """Does the FIFO offer an item to its consumer in this cycle? (It was non-empty at the start of the cycle.)"""
        return self._start - self._pops > 0

    def try_pop(self):
        """
        The consumer asserts READY. If the FIFO is VALID the handshake fires and the item is returned.
        [Returns] an Item, or None if the FIFO had nothing to offer
        """
        self.sig["ready_out"] = True
        self.sig["valid_out"] = self.valid()
        if not self.valid():
            return None
        item = self.items.popleft()
        self._pops += 1
        self.transfers += 1
        self.sig["fire_out"], self.sig["data_out"] = True, item.value
        return item

    def peek(self):
        """The item the FIFO would hand out now (without popping it), or None."""
        return self.items[0] if self.valid() else None

    # ---- producer side -------------------------------------------------------------------------------------------

    def ready(self):
        """Can the FIFO accept an item in this cycle? (registered: room at the start of the cycle; see comb_ready)"""
        used = self._start + self._pushes - (self._pops if self.comb_ready else 0)
        return used < self.depth

    def try_push(self, item):
        """
        The producer asserts VALID with `item`. If the FIFO is READY the handshake fires.
        [Returns] True if the item was accepted
        """
        self.sig["valid_in"], self.sig["data_in"] = True, item.value
        self.sig["ready_in"] = self.ready()
        if not self.ready():
            return False
        self.items.append(item)
        self._pushes += 1
        self.sig["fire_in"] = True
        return True

    def __len__(self):
        return len(self.items)


def _pattern(p, rng):
    """
    Turn a willingness pattern into a function cycle -> bool.

    [Args] p: None (always), a float in (0, 1] (willing with that probability, using rng), a string of '1'/'0'
        characters repeated cyclically (e.g. "110" = two cycles on, one off), or a function of the cycle
    [Edge cases] An empty string or a probability <= 0 raises ValueError (a component that is never willing would
        just deadlock the circuit).
    """
    if p is None:
        return lambda t: True
    if callable(p):
        return p
    if isinstance(p, str):
        if not p or "1" not in p:
            raise ValueError("a pattern string needs at least one '1'")
        return lambda t: p[t % len(p)] == "1"
    if not 0 < p <= 1:
        raise ValueError("a probability pattern must be in (0, 1]")
    return lambda t: rng.random() < p


class Source:
    """
    Produces a sequence of values into one or more FIFOs.

    [Args] outs: list of FIFOs; values: the values to send, in order; pattern: when the source is willing to send
        (see _pattern); route: function item index -> index into outs (default: always outs[0])
    [Stats] sent, stalled (cycles it had data and wanted to send but the FIFO was full = back-pressure)
    [Edge cases] A source that is blocked keeps offering the SAME item (valid stays high until it fires: the
        AXI-style rule that a sender may not withdraw or change data while waiting).
    """

    def __init__(self, name, outs, values, pattern=None, route=None, rng=None):
        self.name, self.outs, self.values = name, outs, list(values)
        self.willing = _pattern(pattern, rng)
        self.route = route or (lambda i: 0)
        self.sent, self.stalled = 0, 0
        self._pending = False            # True once the source has asserted valid for the current item

    def done(self):
        return self.sent >= len(self.values)

    def step(self, t):
        if self.done():
            return
        if not (self._pending or self.willing(t)):
            return
        out = self.outs[self.route(self.sent)]
        if out.try_push(Item(self.values[self.sent], self.sent, t)):
            self.sent += 1
            self._pending = False
        else:
            self.stalled += 1
            self._pending = True


class Sink:
    """
    Consumes items from one or more FIFOs.

    [Args] ins: list of FIFOs; pattern: when the sink is ready (see _pattern); route: function item index -> index
        into ins (default: always ins[0]), i.e. the ORDER in which the sink reads its inputs
    [Stats] received: list of (cycle, Item); starved: cycles it was ready but its FIFO was empty
    """

    def __init__(self, name, ins, pattern=None, route=None, rng=None):
        self.name, self.ins = name, ins
        self.willing = _pattern(pattern, rng)
        self.route = route or (lambda i: 0)
        self.received, self.starved = [], 0

    def done(self):
        return True                        # a sink has no work of its own: the run ends when the data stops

    def step(self, t):
        if not self.willing(t):
            return
        item = self.ins[self.route(len(self.received))].try_pop()
        if item is None:
            self.starved += 1
        else:
            self.received.append((t, item))

    def values(self):
        """The values received, in order."""
        return [item.value for _, item in self.received]

    def latencies(self):
        """Cycles from creation to arrival of every received item."""
        return [t - item.born for t, item in self.received]

    def throughput(self):
        """
        Steady-state items per cycle: (n - 1) / (cycle of last arrival - cycle of first arrival).
        [Edge cases] Fewer than 2 items: 0.0.
        """
        if len(self.received) < 2:
            return 0.0
        return (len(self.received) - 1) / (self.received[-1][0] - self.received[0][0])


class Stage:
    """
    A pipelined processing block: takes an item, applies fn, emits the result `latency` cycles later.

    [Args] inp, out: FIFOs; fn: function value -> value; latency: cycles from input to output (>= 1);
        ii: initiation interval (accepts a new item at most every ii cycles)
    [Idea] Up to `latency` items can be in flight (one per pipeline register). If the output FIFO is not ready,
        the finished item waits at the end of the pipeline and the items behind it bunch up; when the pipeline is
        full the stage stops accepting input -- back-pressure propagates upstream. (This is an "elastic" pipeline
        whose stages each have a valid bit; a pipeline with one global stall signal behaves the same at its ports.)
    [Stats] busy (cycles with at least one item in flight), blocked (cycles its finished item could not leave)
    """

    def __init__(self, name, inp, out, fn=None, latency=1, ii=1):
        if latency < 1 or ii < 1:
            raise ValueError("latency and ii must be >= 1")
        self.name, self.inp, self.out = name, inp, out
        self.fn = fn or (lambda v: v)
        self.latency, self.ii = latency, ii
        self.pipe = deque()                # [Item, cycle when its result is ready]
        self._last_accept = -10 ** 9
        self.busy, self.blocked = 0, 0

    def done(self):
        return not self.pipe

    def step(self, t):
        if self.pipe:
            self.busy += 1
        if self.pipe and self.pipe[0][1] <= t:
            item, _ = self.pipe[0]
            if self.out.try_push(item):
                self.pipe.popleft()
            else:
                self.blocked += 1
        if len(self.pipe) < self.latency and t - self._last_accept >= self.ii:
            item = self.inp.try_pop()
            if item is not None:
                self.pipe.append((Item(self.fn(item.value), item.serial, item.born), t + self.latency))
                self._last_accept = t

    def computing(self, t):
        """True if some item in flight is still being computed (progress is being made)."""
        return any(ready > t for _, ready in self.pipe)


class Fork:
    """
    Copies every input item to all outputs. Fires only when ALL outputs are ready (a synchronized fork).
    [Edge cases] If one branch is full, the other branches wait too -- the reason fork/join paths need balanced
        buffering.
    """

    def __init__(self, name, inp, outs):
        self.name, self.inp, self.outs = name, inp, outs

    def done(self):
        return True

    def step(self, t):
        if self.inp.valid() and all(o.ready() for o in self.outs):
            item = self.inp.try_pop()
            for o in self.outs:
                o.try_push(Item(item.value, item.serial, item.born))


class Join:
    """
    Combines one item from each input into one output item: out = fn([v0, v1, ...]).
    Fires only when every input is valid and the output is ready.
    [Edge cases] The combined item keeps the earliest birth cycle of its parts.
    """

    def __init__(self, name, ins, out, fn=None):
        self.name, self.ins, self.out = name, ins, out
        self.fn = fn or (lambda vs: tuple(vs))

    def done(self):
        return True

    def step(self, t):
        if all(i.valid() for i in self.ins) and self.out.ready():
            items = [i.try_pop() for i in self.ins]
            self.out.try_push(Item(self.fn([it.value for it in items]), items[0].serial,
                                   min(it.born for it in items)))


class RunResult:
    """Outcome of Circuit.run(): cycles simulated, status ("done", "deadlock" or "timeout"), optional trace."""

    def __init__(self, cycles, status, trace):
        self.cycles, self.status, self.trace = cycles, status, trace


class Circuit:
    """
    A collection of FIFOs and components, simulated cycle by cycle.

    [Usage] create FIFOs with fifo(), components with source()/stage()/fork()/join()/sink() (in data-flow order),
        then run().
    """

    def __init__(self, seed=0):
        self.fifos, self.parts = [], []
        self.rng = random.Random(seed)       # every random pattern draws from this seeded generator

    def fifo(self, name, depth=2, comb_ready=False):
        f = Fifo(name, depth, comb_ready)
        self.fifos.append(f)
        return f

    def _add(self, part):
        self.parts.append(part)
        return part

    def source(self, name, outs, values, pattern=None, route=None):
        outs = outs if isinstance(outs, list) else [outs]
        return self._add(Source(name, outs, values, pattern, route, self.rng))

    def sink(self, name, ins, pattern=None, route=None):
        ins = ins if isinstance(ins, list) else [ins]
        return self._add(Sink(name, ins, pattern, route, self.rng))

    def stage(self, name, inp, out, fn=None, latency=1, ii=1):
        return self._add(Stage(name, inp, out, fn, latency, ii))

    def fork(self, name, inp, outs):
        return self._add(Fork(name, inp, outs))

    def join(self, name, ins, out, fn=None):
        return self._add(Join(name, ins, out, fn))

    def busy(self):
        """True while work remains: an unfinished source, a non-empty FIFO, or a stage with items in flight."""
        return any(not p.done() for p in self.parts) or any(len(f) for f in self.fifos)

    def run(self, max_cycles=100_000, stall_limit=64, trace=False):
        """
        Simulate until all work is done, a deadlock is detected, or max_cycles pass.

        [Args] trace: if True, record every FIFO's signals in every cycle (for waveform tables)
        [Returns] RunResult(cycles, status, trace) where trace is a list (one entry per cycle) of
            {fifo name: signal dict} and cycles is the number of cycles until the last movement + 1
        [Edge cases] "deadlock": nothing moved for stall_limit cycles and no stage was still computing, while
            work remains. "timeout": max_cycles reached.
        """
        rec, idle, last_active = [], 0, 0
        for t in range(max_cycles):
            if not self.busy():
                return RunResult(last_active + 1, "done", rec)
            for f in self.fifos:
                f._begin()
            for p in reversed(self.parts):          # consumers first (see the timing model)
                p.step(t)
            moved = any(f.sig["fire_in"] or f.sig["fire_out"] for f in self.fifos)
            computing = any(isinstance(p, Stage) and p.computing(t) for p in self.parts)
            for f in self.fifos:
                f._end()
            if trace:
                rec.append({f.name: dict(f.sig, occ=len(f)) for f in self.fifos})
            if moved:
                last_active = t
            idle = 0 if (moved or computing) else idle + 1
            if idle >= stall_limit:
                return RunResult(last_active + 1, "deadlock", rec)
        return RunResult(max_cycles, "timeout", rec)


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

if __name__ == "__main__":
    # 1. A FIFO with registered ready and depth 1 halves the throughput; depth 2 restores it; comb_ready fixes depth 1.
    def chain(depth, comb):
        c = Circuit()
        fs = [c.fifo(f"f{i}", depth, comb) for i in range(4)]
        c.source("src", fs[0], range(200))
        for i in range(3):
            c.stage(f"s{i}", fs[i], fs[i + 1], latency=1)
        snk = c.sink("snk", fs[3])
        r = c.run()
        assert r.status == "done" and snk.values() == list(range(200))
        return snk.throughput()
    assert abs(chain(1, False) - 0.5) < 0.01, chain(1, False)
    assert chain(2, False) == 1.0 and chain(1, True) == 1.0
    # 2. Stage function and latency.
    c = Circuit()
    a, b = c.fifo("a"), c.fifo("b")
    c.source("src", a, range(5))
    c.stage("x3", a, b, fn=lambda v: 3 * v, latency=4)
    snk = c.sink("snk", b)
    assert c.run().status == "done" and snk.values() == [0, 3, 6, 9, 12]
    # 3. Deadlock: the source alternates between two FIFOs, the sink reads 4 from one then 4 from the other.
    def alt(depth):
        c = Circuit()
        fa, fb = c.fifo("A", depth), c.fifo("B", depth)
        c.source("src", [fa, fb], range(16), route=lambda i: i % 2)
        snk = c.sink("snk", [fa, fb], route=lambda i: (i // 4) % 2)
        return c.run().status, len(snk.received)
    assert alt(2)[0] == "deadlock" and alt(3) == ("done", 16), (alt(2), alt(3))
    # 4. Fork/join with unbalanced branches: enough buffering on the short branch gives full throughput.
    def forkjoin(d_short, lat=8):
        c = Circuit()
        f0, s_in, l_in, l_out, out = (c.fifo(n) for n in ("in", "short", "long_in", "long_out", "out"))
        s_in.depth = d_short
        c.source("src", f0, range(100))
        c.fork("fork", f0, [s_in, l_in])
        c.stage("long", l_in, l_out, latency=lat)
        c.join("join", [s_in, l_out], out, fn=sum)
        snk = c.sink("snk", out)
        assert c.run().status == "done" and snk.values() == [2 * v for v in range(100)]
        return snk.throughput()
    assert forkjoin(1) < 0.5 and forkjoin(12) == 1.0
    print("channels.py self-test passed")
