"""Reproduce every figure of Bishop and Bishop (2024) covered by the course.

usage:
    python3 make_all.py             # all figures, then the private test scripts listed in README.md
    python3 make_all.py --figures   # figures only
    python3 make_all.py --checks    # the private test scripts only
    python3 make_all.py 6 7         # only Chapters 6 and 7
    python3 make_all.py 0           # only the appendices (appendices.py)

Each chapter module can also be run on its own, e.g.
    python3 ch06_deep_neural_networks.py --list
    python3 ch06_deep_neural_networks.py --fig 6.4
"""
import os

for _v in ("OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "OMP_NUM_THREADS"):
    os.environ.setdefault(_v, "1")

import argparse
import glob
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))


def main():
    p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    p.add_argument("chapters", nargs="*", type=int, help="chapter numbers, 0 for the appendices (default: all)")
    p.add_argument("--figures", action="store_true", help="only make the figures")
    p.add_argument("--checks", action="store_true", help="only run the private test scripts listed in README.md")
    a = p.parse_args()
    chapters = a.chapters or list(range(1, 21)) + [0]
    failed = []
    for ch in chapters:
        scripts = []
        fig_glob, chk_glob = ("appendices.py", "checks_appendices.py") if ch == 0 else ("ch%02d_*.py" % ch, "checks_ch%02d*.py" % ch)
        if a.figures or not a.checks:
            scripts += sorted(glob.glob(os.path.join(HERE, fig_glob)))
        if a.checks or not a.figures:
            scripts += sorted(glob.glob(os.path.join(HERE, chk_glob)))
        for s in scripts:
            print("\n====", os.path.basename(s), flush=True)
            if subprocess.call([sys.executable, s], cwd=HERE) != 0:
                failed.append(os.path.basename(s))
    print("\nfailed:" if failed else "\nall scripts ran cleanly", " ".join(failed))
    sys.exit(1 if failed else 0)


if __name__ == "__main__":
    main()
