"""
forksim.py -- enumerate every possible output of a tiny fork() program.

[Idea]
  A program made only of print statements and fork() calls has a deterministic
  SET of possible outputs, even though any single run picks one order at random.
  The reason: fork() turns one process into two that run the SAME remaining code
  independently. The prints form a partial order (a "process graph", CS:APP
  chapter 8):
    - within one process, prints happen in program order (an edge earlier->later);
    - a print in the parent and a print in the child, both after a fork, are
      UNORDERED with respect to each other -- either may come first.
  The possible outputs are exactly the linear extensions (topological sorts) of
  that partial order, read off as label strings. This module builds the graph
  and enumerates them -- the deterministic answer to "what can this print?".

[Why a simulator here]
  Real fork() output races: you cannot SEE all orderings by running it, only one
  per run. The slides draw the process graph by hand; this does it mechanically
  so you can check the hand analysis of any small snippet. It is a TEACHING tool,
  not a lab deliverable -- it models print/fork only, not real process behaviour.

[Python tip]
  Everything is sorted before it is printed or iterated, so the output is
  byte-identical across Python versions (no reliance on set/dict ordering).
"""

# A "program" is a list of instructions. Each instruction is one of:
#     ("print", "<label>")   emit a one-character (or short) label
#     ("fork",)              split the current process into two
Program = list


def _build_graph(instrs):
    """Build the DAG of print events.

    Returns (labels, preds) where:
      labels[k] is the string printed by node k (nodes numbered 0,1,2,... in
                a deterministic creation order);
      preds[k]  is the set of node ids that must print before node k.

    [Idea] We expand the program process by process. Processing instrs[i:] as
    one process, each fork spawns a parallel process that also runs instrs[i+1:]
    (recursively), starting "after" the same last print -- which is exactly how
    fork duplicates the continuation.
    """
    labels = []
    preds = {}
    counter = [0]  # mutable integer shared across the nested helper

    def new_node(label, prev):
        k = counter[0]
        counter[0] += 1
        labels.append(label)
        preds[k] = set() if prev is None else {prev}
        return k

    def expand(i, prev):
        # `prev` is the last print node that precedes everything from here, or None.
        last = prev
        while i < len(instrs):
            op = instrs[i]
            if op[0] == "print":
                last = new_node(op[1], last)
            elif op[0] == "fork":
                # The child runs the rest independently, starting after `last`.
                expand(i + 1, last)
                # The parent simply continues the loop with the rest.
            i += 1

    expand(0, None)
    return labels, preds


def _linear_extensions(labels, preds):
    """Yield every topological ordering of the nodes, each as a tuple of labels.

    [Idea] Repeatedly place any node whose predecessors are all already placed.
    Trying every such choice, in sorted node order, enumerates all orders. We
    collect the DISTINCT label strings (two different node orders can print the
    same string, e.g. two processes both printing 'b').
    """
    n = len(labels)
    results = set()
    placed = []
    used = [False] * n

    def recurse():
        if len(placed) == n:
            results.add(tuple(labels[k] for k in placed))
            return
        for k in range(n):  # sorted node order -> deterministic traversal
            if used[k]:
                continue
            if all(used[p] for p in preds[k]):
                used[k] = True
                placed.append(k)
                recurse()
                placed.pop()
                used[k] = False

    recurse()
    return sorted(results)  # sorted -> byte-identical output across versions


def analyze(instrs):
    """Return a dict summarizing a program's possible outputs.

    Keys: n_forks, n_processes (upper bound 2**forks on a straight-line program),
          n_prints, n_distinct_outputs, outputs (sorted list of label-tuples).
    """
    labels, preds = _build_graph(instrs)
    n_forks = sum(1 for op in instrs if op[0] == "fork")
    outs = _linear_extensions(labels, preds)
    return {
        "n_forks": n_forks,
        "n_prints": len(labels),
        "n_distinct_outputs": len(outs),
        "outputs": outs,
    }


def possible(instrs, candidate):
    """Is the string `candidate` (e.g. 'abba') a possible output? (True/False)"""
    labels, preds = _build_graph(instrs)
    target = tuple(candidate)
    for out in _linear_extensions(labels, preds):
        if out == target:
            return True
    return False


# Convenience constructors so callers read like the C they model.
def P(label):
    return ("print", label)


def FORK():
    return ("fork",)
