#!/usr/bin/env python3
"""
01_process_graph.py -- the classic "what can this fork program print?" puzzles.

[Idea]
  Running a fork() program shows you ONE output. The exam question is: what are
  ALL the possible outputs, and which strings are impossible? forksim.py answers
  it by building the process graph and listing its linear extensions. We run it
  on three snippets of growing trickiness and check a few "is this possible?"
  claims.

Run:   python3 01_process_graph.py      (make run builds nothing for this one)

[Python tip]
  The output is identical under Python 3.9 and 3.13: forksim sorts every set
  before printing, so nothing depends on hash ordering.
"""
import course_path  # noqa: F401  (kept for symmetry with other lectures)
from forksim import analyze, possible, P, FORK


def show(title, instrs, source):
    print(f"== {title} ==")
    for line in source:
        print(f"    {line}")
    r = analyze(instrs)
    print(f"  forks={r['n_forks']}  processes(max)={2 ** r['n_forks']}  "
          f"print-events={r['n_prints']}  distinct outputs={r['n_distinct_outputs']}")
    outs = ["".join(o) for o in r["outputs"]]
    if len(outs) <= 12:
        print("  possible outputs: " + ", ".join(outs))
    else:
        print("  possible outputs (first 12 of %d): %s, ..." %
              (len(outs), ", ".join(outs[:12])))
    print()


def main():
    # --- Snippet 1: a print before a single fork, then a print after. --------
    s1 = [P("a"), FORK(), P("b")]
    show("snippet 1: printf(a); fork(); printf(b);",
         s1,
         ['printf("a");', "fork();", 'printf("b");'])

    # --- Snippet 2: two forks make four processes. ---------------------------
    s2 = [FORK(), P("a"), FORK(), P("b")]
    show("snippet 2: fork(); printf(a); fork(); printf(b);",
         s2,
         ["fork();", 'printf("a");', "fork();", 'printf("b");'])

    # --- Snippet 3: a fork between two prints, nested effect. -----------------
    s3 = [P("0"), FORK(), P("1"), FORK(), P("2")]
    show("snippet 3: printf(0); fork(); printf(1); fork(); printf(2);",
         s3,
         ['printf("0");', "fork();", 'printf("1");', "fork();", 'printf("2");'])

    # --- A few "is this output possible?" checks (classic exam traps). -------
    print("== possibility checks ==")
    # Note: possible() asks about a COMPLETE output, so every candidate has the
    # program's full print-count length (3 for s1, 6 for s2).
    checks = [
        (s1, "abb", True),      # a is always first; both b's follow
        (s1, "bab", False),     # impossible: a happens-before every b
        (s2, "aabbbb", True),   # both a's, then all four b's
        (s2, "ababbb", True),   # a b interleaved with the second a
        (s2, "bbaabb", False),  # impossible: the first printed char is always a
    ]
    for instrs, cand, expect in checks:
        got = possible(instrs, cand)
        tag = "OK " if got == expect else "!! "
        print(f"  {tag}'{cand}' possible? {got}  (expected {expect})")
    print()

    print("Observations")
    print("------------")
    print("- snippet 1 prints 'a' once (before the fork) and 'b' twice (two")
    print("  processes after it): the ONLY output is 'abb'. 'bab' is impossible")
    print("  because 'a' happens-before every 'b'.")
    print("- each fork can double the process count: snippet 2 has 2 forks -> up")
    print("  to 4 processes and several interleavings of the b's among the a's.")
    print("- the enumerator agrees with the hand-drawn process graph, and flags")
    print("  the impossible orders a human often gets wrong.")


if __name__ == "__main__":
    main()
