#!/usr/bin/env python3
# $Id: ppdemo_workflow 283 2026-10-21 13:52:43Z peter $
#
# ppdemo_workflow --- run the WHOLE workflow of packpay on one or many KiCad schematics, stage by stage,
# with a time limit per stage, and say what came out.
#
# ADDED 2026-10-21 (0.72.138), on the author's word ("the demo running harness should be part of the
# project with all the documentation that it incurs"). It was a scratch script of 2026-10-20, with
# which the whole workflow was run on KiCad's own demonstration designs (ResearchJournal.org,
# continued 33): fourteen designs, a dozen defects found and mended, six more recorded. It is run ON
# DEMAND, never as part of an iteration (the larger designs take an hour); the check of
# pptest_regression runs it on one small design.
#
# The stages, for each schematic (a stage that cannot run says why and the next ones go on where they can):
#   netlist       kicad-cli's netlist of the source
#   pprender      the breadboard drawing (a design over the component limit is run again with the limit raised, and says so)
#   instructions  ppbuild_instructions in English and in the algebraic notation (the strip dialect; the hole dialect too)
#   readback      the instructions read back (parse_instructions) against the source: nets of two or more parts
#   loop          ppextract_sources and ppresolve_components: a schematic from the instructions, against the source
#   generator     ppkicad_layout (schematic to schematic), then kicad-cli ERC, against the source
# One result.json per schematic and a summary table (summary.org) for all of them. The comparison is by
# REFERENCES (the nets of two or more parts, as sets of references) and by EXACT PINS. The instructions carry
# no pin identities for the parts that are not anchors: a reading equal by references and different by exact
# pins is the expected state, an equal generator output by exact pins is the one that counts.

import json
import os
import re
import subprocess
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)


def _version():
    """This project's own current Dewey-decimal version (see ppnetlist's own identical helper)."""
    try:
        with open(os.path.join(HERE, "VERSION")) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#"):
                    return line
    except OSError:
        pass
    return "unknown"


def _fail(message, status=1):
    print(f"ppdemo_workflow: {message}", file=sys.stderr)
    raise SystemExit(status)


# ---------------------------------------------------------------------------------------------------------------------------
# finding the schematics

def default_demos_dir():
    """Where KiCad's demonstration designs are: $KICAD_DEMOS_DIR, else the cache of fetch-kicad-demos (git), else KiCad's own directory."""
    env = os.environ.get("KICAD_DEMOS_DIR")
    if env:
        return env
    cache = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache"), "packpay", "kicad-demos", "git", "demos")
    return cache if os.path.isdir(cache) else "/usr/share/kicad/demos"


def root_schematics(folder):
    """The root schematics of a folder: the X.kicad_sch that has an X.kicad_pro beside it (a sheet of a hierarchy has none), sorted. A folder is searched one level down, not deeper."""
    found = []
    for name in sorted(os.listdir(folder)):
        if name.endswith(".kicad_sch") and os.path.exists(os.path.join(folder, name[:-len(".kicad_sch")] + ".kicad_pro")):
            found.append(os.path.join(folder, name))
    return found


def demo_schematics(demos_dir):
    """Every root schematic of the folders of a demonstration directory: [(label, path)]. The label is the folder's name, and folder-stem when a folder has several."""
    out = []
    for folder in sorted(os.listdir(demos_dir)):
        full = os.path.join(demos_dir, folder)
        if not os.path.isdir(full):
            continue
        roots = root_schematics(full)
        for path in roots:
            stem = os.path.splitext(os.path.basename(path))[0]
            out.append((folder if len(roots) == 1 else f"{folder}-{stem}", path))
    return out


# ---------------------------------------------------------------------------------------------------------------------------
# the comparison

def _nets_by_ref(node_lists, refs):
    out = set()
    for nodes in node_lists:
        rs = frozenset(r for r, _ in nodes if r in refs)
        if len(rs) >= 2:
            out.add(rs)
    return out


def _nets_exact(node_lists, refs):
    out = set()
    for nodes in node_lists:
        ns = frozenset((r, str(p)) for r, p in nodes if r in refs)
        if len(ns) >= 2:
            out.add(ns)
    return out


def compare_nets(orig_nodes, other_nodes, refs, label):
    """The nets of two or more parts of `other` against those of `orig`, restricted to `refs`: by references, and by exact pins."""
    a_ref, b_ref = _nets_by_ref(orig_nodes, refs), _nets_by_ref(other_nodes, refs)
    a_ex, b_ex = _nets_exact(orig_nodes, refs), _nets_exact(other_nodes, refs)
    return {"label": label, "parts": len(refs), "nets_orig": len(a_ref), "nets_other": len(b_ref),
            "same_ref_partition": a_ref == b_ref, "same_exact_partition": a_ex == b_ex,
            "ref_only_orig": len(a_ref - b_ref), "ref_only_other": len(b_ref - a_ref),
            "sample_only_orig": [sorted(x) for x in list(a_ref - b_ref)[:2]], "sample_only_other": [sorted(x) for x in list(b_ref - a_ref)[:2]]}


# ---------------------------------------------------------------------------------------------------------------------------
# one schematic

def _limit_hit(r):
    """A stage refused because of the component limit (the message names it)."""
    t = r["err"] + r["out"]
    return r["rc"] not in (0, None) and ("max-components" in t or "max_components" in t or "component limit" in t or "component-count limit" in t
                                         or "too many components" in t.lower() or ("exceeds" in t.lower() and "components" in t.lower()))


def run_workflow(sch, out, kicad_cli, stage_timeout=1500, generator_timeout=2400, reuse=False, keep_limit=False, say=None):
    """The whole workflow on one schematic, into the directory `out`; returns (and writes, as result.json) the dictionary of the stages. `reuse`: the drawing and the instruction files
    of an earlier run in `out` are read instead of made again. `keep_limit`: a design over the component limit is not run again with the limit raised."""
    from netlist import load_from_schematic
    import parse_instructions as PI

    say = say or (lambda msg: None)
    sch, out = os.path.abspath(sch), os.path.abspath(out)      # the stages run in the output directory: every path must be absolute
    name = os.path.splitext(os.path.basename(sch))[0]
    os.makedirs(out, exist_ok=True)
    R = {"demo": name, "schematic": os.path.abspath(sch), "version": _version(), "stages": {}}
    env = dict(os.environ, PYTHONPATH=HERE)
    cli = kicad_cli.split()

    def save():
        with open(os.path.join(out, "result.json"), "w") as f:
            json.dump(R, f, indent=1)

    def run(cmd, timeout=stage_timeout):
        t = time.time()
        try:
            r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, cwd=out, env=env)
            return {"rc": r.returncode, "secs": round(time.time() - t, 1), "out": r.stdout, "err": r.stderr, "timeout": False}
        except subprocess.TimeoutExpired as e:
            def text(x):
                return x.decode(errors="replace") if isinstance(x, bytes) else (x or "")
            return {"rc": None, "secs": round(time.time() - t, 1), "out": text(e.stdout), "err": text(e.stderr), "timeout": True}

    def brief(r, n=400):
        text = (r["err"] + r["out"]).strip().splitlines()
        return {"rc": r["rc"], "secs": r["secs"], "timeout": r["timeout"], "tail": " | ".join(text[-3:])[:n]}

    def tool(*args):
        return [sys.executable, os.path.join(HERE, args[0])] + list(args[1:])

    # ---- the netlist of the source
    say(f"{name}: netlist")
    t = time.time()
    try:
        nl = load_from_schematic(sch, kicad_cli=kicad_cli)
        R["stages"]["netlist"] = {"ok": True, "secs": round(time.time() - t, 1), "parts": len(nl.components), "nets": len(nl.nets), "sheets": len({p for p, _ in nl.sheets})}
    except Exception as e:  # noqa: BLE001
        R["stages"]["netlist"] = {"ok": False, "error": f"{type(e).__name__}: {e}"[:300]}
        save()
        return R
    save()
    parts = len(nl.components)
    orig_nodes = [n.nodes for n in nl.nets if "unconnected" not in n.name.lower()]

    # ---- the breadboard drawing
    say(f"{name}: drawing")
    extra = []
    reused = reuse and os.path.exists(os.path.join(out, "instr-english.txt"))
    if reused:
        r = {"rc": 0, "secs": 0, "out": "", "err": "", "timeout": False}
        R["stages"]["pprender"] = {"rc": 0, "secs": 0, "timeout": False, "tail": "reused"}
    else:
        r = run(tool("pprender", sch, "-o", os.path.join(out, "board.svg"), "--quiet", "--kicad-cli", kicad_cli))
        R["stages"]["pprender"] = brief(r)
    if _limit_hit(r) and not keep_limit:
        R["stages"]["pprender"]["limit_refused"] = True
        extra = ["--max-components", str(parts + 10)]
        r = run(tool("pprender", sch, "-o", os.path.join(out, "board.svg"), "--quiet", "--kicad-cli", kicad_cli) + extra)
        R["stages"]["pprender_raised"] = brief(r)
    save()

    # ---- the instructions
    texts = {}
    final = R["stages"].get("pprender_raised") or R["stages"]["pprender"]
    skip_instr = bool(final.get("timeout")) or final.get("rc") != 0
    if skip_instr:
        R["stages"]["instructions_skipped"] = "the drawing stage ended with rc=%r timeout=%r: %s" % (final.get("rc"), final.get("timeout"), final.get("tail", "")[:200])
    for tag, args, ext in (("english", [], "txt"), ("strips", ["--format", "algebraic", "--dialect", "strips"], "ban")):
        if skip_instr:
            break
        say(f"{name}: instructions ({tag})")
        path = os.path.join(out, f"instr-{tag}.{ext}")
        if reuse and os.path.exists(path):
            with open(path, encoding="utf-8") as f:
                texts[tag] = f.read()
            R["stages"][f"build_{tag}"] = {"rc": 0, "secs": 0, "timeout": False, "lines": texts[tag].count("\n"), "tail": "reused"}
            continue
        cmd = tool("ppbuild_instructions", sch, "-o", path, "--quiet", "--kicad-cli", kicad_cli)
        r = run(cmd + extra + args)
        if _limit_hit(r) and not extra and not keep_limit:
            extra = ["--max-components", str(parts + 10)]
            R["stages"]["limit_refused_instructions"] = True
            r = run(cmd + extra + args)
        R["stages"][f"build_{tag}"] = brief(r)
        if r["rc"] == 0 and os.path.exists(path):
            with open(path, encoding="utf-8") as f:
                texts[tag] = f.read()
            R["stages"][f"build_{tag}"]["lines"] = texts[tag].count("\n")
        save()
    if "english" in texts and R["stages"]["build_english"]["secs"] < 120:
        path = os.path.join(out, "instr-holes.ban")
        if reuse and os.path.exists(path):
            r = {"rc": 0, "secs": 0, "out": "", "err": "", "timeout": False}
        else:
            r = run(tool("ppbuild_instructions", sch, "-o", path, "--quiet", "--kicad-cli", kicad_cli) + extra + ["--format", "algebraic"])
        R["stages"]["build_holes"] = brief(r)
        if r["rc"] == 0 and os.path.exists(path):
            with open(path, encoding="utf-8") as f:
                texts["holes"] = f.read()
    save()

    # ---- the instructions read back
    say(f"{name}: readback")
    placed = None
    sets = {}
    for tag, text in texts.items():
        t = time.time()
        try:
            steps = PI.parse_instructions(text)
            nl2, _pl = PI.reconstruct(steps, board_config=PI.board_config_for(text))
            refs = set(nl2.components) & set(nl.components)
            placed = placed or refs
            c = compare_nets(orig_nodes, [n.nodes for n in nl2.nets], refs, tag)
            c.update(ok=True, secs=round(time.time() - t, 1), unplaced=len(set(nl.components) - set(nl2.components)), unknown=len(set(nl2.components) - set(nl.components)))
            R["stages"][f"readback_{tag}"] = c
            sets[tag] = {(n.name, tuple(sorted(map(tuple, ([str(a), str(b)] for a, b in n.nodes))))) for n in nl2.nets}
        except Exception as e:  # noqa: BLE001
            R["stages"][f"readback_{tag}"] = {"ok": False, "error": f"{type(e).__name__}: {e}"[:300]}
    if sets:
        tags = sorted(sets)
        R["stages"]["dialects_agree"] = {"tags": tags, "same_netlist": all(sets[t_] == sets[tags[0]] for t_ in tags)}
    save()

    # ---- the loop: sources, then a schematic from the instructions
    if "english" in texts:
        say(f"{name}: loop")
        src = os.path.join(out, "sources.json")
        r = run(tool("ppextract_sources", sch, "-o", src, "--portable", "--quiet", "--kicad-cli", kicad_cli))
        R["stages"]["extract_sources"] = brief(r)
        if r["rc"] == 0:
            for tag in ("english", "strips"):
                if tag not in texts:
                    continue
                loop = os.path.join(out, f"loop-{tag}.kicad_sch")
                ins = os.path.join(out, "instr-english.txt" if tag == "english" else "instr-strips.ban")
                cmd = tool("ppresolve_components", ins, "--sources", src, "-o", loop, "--quiet", "--kicad-cli", kicad_cli) + extra
                r = run(cmd)
                filled = 0
                for _round in range(4):
                    if r["rc"] == 0 or "could not be identified" not in (r["err"] + r["out"]):
                        break
                    # the pin_map that only a user can write: here it is taken from the source schematic (the net name of the instructions -> the part's pin(s) on the net of that name)
                    with open(src) as f:
                        data = json.load(f)
                    pm = data.setdefault("pin_map", {})
                    byname = {}
                    for n in nl.nets:
                        byname[n.name] = n
                        byname[n.name.lstrip("/")] = n
                        byname[n.name.rsplit("/", 1)[-1]] = n
                    added = 0
                    for m in re.finditer(r"^\s+(\S+): net '(.*)' \(synthetic pin", r["err"] + r["out"], re.M):
                        ref_, net_ = m.group(1), m.group(2)
                        n = byname.get(net_) or byname.get(net_.replace("#net", ""))
                        if not n:
                            continue
                        pins_ = [str(p) for rr, p in n.nodes if rr == ref_]
                        if pins_:
                            pm.setdefault(ref_, {})[net_] = pins_[0] if len(pins_) == 1 else pins_
                            added += 1
                    if not added:
                        break
                    filled += added
                    with open(src, "w") as f:
                        json.dump(data, f, indent=1)
                    r = run(cmd)
                R["stages"][f"resolve_{tag}"] = brief(r)
                R["stages"][f"resolve_{tag}"]["pin_map_entries_filled_from_source"] = filled
                if r["rc"] == 0 and os.path.exists(loop):
                    try:
                        nl3 = load_from_schematic(loop, kicad_cli=kicad_cli)
                        refs = (placed or set(nl.components)) & set(nl3.components)
                        c = compare_nets(orig_nodes, [n.nodes for n in nl3.nets], refs, f"loop-{tag}")
                        c["loop_parts"] = len(nl3.components)
                        R["stages"][f"loop_{tag}"] = c
                    except Exception as e:  # noqa: BLE001
                        R["stages"][f"loop_{tag}"] = {"ok": False, "error": f"{type(e).__name__}: {e}"[:300]}
                save()

    # ---- the schematic generator and kicad-cli ERC
    say(f"{name}: generator")
    gen = os.path.join(out, "gen.kicad_sch")
    r = run(tool("ppkicad_layout", sch, "-o", gen, "--quiet", "--kicad-cli", kicad_cli), timeout=generator_timeout)
    R["stages"]["ppkicad_layout"] = brief(r)
    if r["rc"] == 0 and os.path.exists(gen):
        try:
            nl4 = load_from_schematic(gen, kicad_cli=kicad_cli)
            c = compare_nets(orig_nodes, [n.nodes for n in nl4.nets], set(nl.components) & set(nl4.components), "gen")
            c["gen_parts"] = len(nl4.components)
            subprocess.run(cli + ["sch", "erc", "--severity-error", "-o", gen + ".rpt", gen], capture_output=True, text=True)
            rpt = ""
            if os.path.exists(gen + ".rpt"):
                with open(gen + ".rpt") as f:
                    rpt = f.read()
            c["erc_errors"] = len(re.findall(r"^\[\w+\]: ", rpt, re.M))
            c["sheets"] = len({p for p, _ in nl4.sheets})
            R["stages"]["gen_check"] = c
        except Exception as e:  # noqa: BLE001
            R["stages"]["gen_check"] = {"ok": False, "error": f"{type(e).__name__}: {e}"[:300]}
    R["done"] = True
    save()
    return R


# ---------------------------------------------------------------------------------------------------------------------------
# the summary

def _equal_text(c):
    """A comparison in one phrase: equal by pins, equal by references only, or the number of nets that differ."""
    if not isinstance(c, dict):
        return "-"
    if c.get("ok") is False:
        return "error"
    if c.get("same_exact_partition"):
        return "equal"
    if c.get("same_ref_partition"):
        return "equal (refs)"
    return f"{max(c.get('ref_only_orig', 0), c.get('ref_only_other', 0))} net(s) differ"


def verdict(R):
    """The short phrases of the summary for one result: a dictionary of strings."""
    st = R["stages"]
    nlst = st.get("netlist", {})
    v = {"demo": R["demo"], "parts": str(nlst.get("parts", "-"))}
    if not nlst.get("ok"):
        v.update(drawing="-", instructions="-", readback="-", loop="-", generator="-", vs_source="-", erc="-", secs="-")
        v["note"] = "the source could not be read: " + str(nlst.get("error", ""))[:80]
        return v
    pr = st.get("pprender_raised") or st.get("pprender") or {}
    notes = []
    if st.get("pprender", {}).get("limit_refused"):
        notes.append("over the component limit")
    if pr.get("timeout"):
        v["drawing"] = "timeout"
        notes.append(f"drawing: stopped after {pr.get('secs')} s; no instructions")
    elif pr.get("rc") == 0:
        v["drawing"] = "ok"
    else:
        v["drawing"] = "refused"
        tail = pr.get("tail", "")
        notes.append("drawing: " + tail[:90])
    be, bs = st.get("build_english"), st.get("build_strips")
    if be is None:
        v["instructions"] = "-"
    elif be.get("timeout"):
        v["instructions"] = "timeout"
    elif be.get("rc") == 0 and (bs or {}).get("rc") == 0:
        v["instructions"] = f"{be.get('lines', '?')} lines"
    else:
        v["instructions"] = "refused"
        m = re.search(r"ppbuild_instructions: ([^|]*)", be.get("tail", ""))
        notes.append("instructions: " + (m.group(1).strip()[:110] if m else be.get("tail", "")[:110]))
    rb = st.get("readback_english") or st.get("readback_strips") or st.get("readback_holes")
    v["readback"] = _equal_text(rb)
    lp = st.get("loop_english")
    if lp is not None:
        v["loop"] = _equal_text(lp)
    elif "resolve_english" in st:
        v["loop"] = "resolver stopped"
        notes.append("resolver: " + st["resolve_english"].get("tail", "")[-110:])
    else:
        v["loop"] = "-"
    gl = st.get("ppkicad_layout")
    if gl is None:
        v["generator"] = "-"
    elif gl.get("timeout"):
        v["generator"] = "timeout"
    elif gl.get("rc") == 0:
        v["generator"] = "ok"
    else:
        v["generator"] = "refused"
        notes.append("generator: " + gl.get("tail", "")[:110])
    gc = st.get("gen_check")
    v["vs_source"] = _equal_text(gc)
    v["erc"] = str(gc.get("erc_errors", "-")) if isinstance(gc, dict) and "erc_errors" in gc else "-"
    total = sum(s.get("secs", 0) or 0 for s in st.values() if isinstance(s, dict))
    v["secs"] = str(int(round(total)))
    v["note"] = "; ".join(notes)
    return v


COLUMNS = ("demo", "parts", "drawing", "instructions", "readback", "loop", "generator", "vs_source", "erc", "secs")
HEADERS = {"demo": "demo", "parts": "parts", "drawing": "drawing", "instructions": "instructions", "readback": "readback", "loop": "loop",
           "generator": "generator", "vs_source": "generated = source", "erc": "ERC errors", "secs": "seconds"}


def summary_table(results):
    """The Org table of the results (one row per schematic), and under it the notes (a line per schematic that has one)."""
    rows = [verdict(R) for R in results]
    lines = ["| " + " | ".join(HEADERS[c] for c in COLUMNS) + " |", "|" + "+".join("-" * (len(HEADERS[c]) + 2) for c in COLUMNS) + "|"]
    for v in rows:
        lines.append("| " + " | ".join(v[c] for c in COLUMNS) + " |")
    notes = [f"- {v['demo']}: {v['note']}" for v in rows if v.get("note")]
    return "\n".join(lines) + ("\n\nNotes\n" + "\n".join(notes) if notes else "") + "\n"


def load_results(outdir):
    """The result.json files of the subdirectories of `outdir`, sorted by directory name."""
    results = []
    for d in sorted(os.listdir(outdir)):
        p = os.path.join(outdir, d, "result.json")
        if os.path.isfile(p):
            try:
                with open(p) as f:
                    R = json.load(f)
                R["demo"] = d
                results.append(R)
            except (OSError, ValueError):
                continue
    return results


def main(argv=None):
    import argparse

    parser = argparse.ArgumentParser(
        prog="ppdemo_workflow",
        description="Run the whole workflow (netlist, breadboard drawing, instructions in English and in the algebraic notation, the instructions read back, "
                    "a schematic from the instructions, the schematic generator with ERC) on KiCad schematics, with a time limit per stage, and write one result.json per "
                    "schematic and a summary table. Run on demand: the larger designs take an hour.")
    parser.add_argument("targets", nargs="*", metavar="SCHEMATIC|FOLDER",
                        help="a root .kicad_sch file, or a folder (its root schematics: the X.kicad_sch that has an X.kicad_pro beside it)")
    parser.add_argument("--all-demos", nargs="?", const="", default=None, metavar="DIR",
                        help="every folder of a demonstration directory (default: $KICAD_DEMOS_DIR, else the cache of fetch-kicad-demos, else /usr/share/kicad/demos)")
    parser.add_argument("-o", "--output-dir", metavar="DIR", default="demo-workflow", help="where the results go, one subdirectory per schematic (default: demo-workflow)")
    parser.add_argument("--stage-timeout", metavar="SECONDS", type=float, default=1500, help="the limit of a stage (default: 1500)")
    parser.add_argument("--generator-timeout", metavar="SECONDS", type=float, default=2400, help="the limit of ppkicad_layout (default: 2400)")
    parser.add_argument("--reuse", action="store_true", help="read the instruction files of an earlier run in the output directory instead of making them again (the drawing is not made again)")
    parser.add_argument("--keep-limit", action="store_true",
                        help="do not run a design again with the component limit raised when it is over it (the default is to raise it, to see what the tools do)")
    parser.add_argument("--summary-only", action="store_true", help="print the summary of the results already in the output directory; run nothing")
    parser.add_argument("--kicad-cli", metavar="CMD", default=os.environ.get("KICAD_CLI", "kicad-cli"), help="kicad-cli command (default: $KICAD_CLI if set, else 'kicad-cli')")
    parser.add_argument("--quiet", action="store_true", help="suppress informational messages")
    parser.add_argument("--version", action="version", version=f"%(prog)s {_version()}")
    args = parser.parse_args(argv)

    outdir = args.output_dir
    if args.summary_only:
        if not os.path.isdir(outdir):
            _fail(f"{outdir}: no such directory")
        results = load_results(outdir)
        if not results:
            _fail(f"{outdir}: no result.json in its subdirectories")
        print(summary_table(results), end="")
        return 0

    jobs = []
    for target in args.targets:
        if os.path.isdir(target):
            roots = root_schematics(target)
            if not roots:
                _fail(f"{target}: no root schematic in it (an X.kicad_sch with an X.kicad_pro beside it)", 2)
            base = os.path.basename(os.path.abspath(target))
            jobs += [(base if len(roots) == 1 else f"{base}-{os.path.splitext(os.path.basename(p))[0]}", p) for p in roots]
        elif target.endswith(".kicad_sch"):
            if not os.path.isfile(target):
                _fail(f"{target}: no such file")
            jobs.append((os.path.splitext(os.path.basename(target))[0], target))
        else:
            _fail(f"{target}: neither a .kicad_sch file nor a folder", 2)
    if args.all_demos is not None:
        demos = args.all_demos or default_demos_dir()
        if not os.path.isdir(demos):
            _fail(f"{demos}: no such directory (fetch-kicad-demos fetches KiCad's demonstration designs)")
        jobs += demo_schematics(demos)
    if not jobs:
        parser.error("name a schematic or a folder, or --all-demos")
    seen = set()
    for label, _p in jobs:
        if label in seen:
            _fail(f"two schematics would both go to {os.path.join(outdir, label)}: run them one at a time", 2)
        seen.add(label)

    os.makedirs(outdir, exist_ok=True)

    def say(msg):
        if not args.quiet:
            print(f"ppdemo_workflow: {msg}", file=sys.stderr, flush=True)

    results = []
    for label, path in jobs:
        say(f"=== {label} ({path})")
        results.append(run_workflow(path, os.path.join(outdir, label), args.kicad_cli, stage_timeout=args.stage_timeout,
                                    generator_timeout=args.generator_timeout, reuse=args.reuse, keep_limit=args.keep_limit, say=say))
        results[-1]["demo"] = label
    table = summary_table(load_results(outdir))      # every result in the directory, those of earlier runs too
    with open(os.path.join(outdir, "summary.org"), "w", encoding="utf-8") as f:
        f.write(table)
    print(table, end="")
    return 0


if __name__ == "__main__":
    sys.exit(main())
