# SPDX-License-Identifier: Apache-2.0
"""Rebuild whatever is stale, in pipeline order, then validate.

    ~/.venvs/goldfish-cad/bin/python v01/build.py            # stale steps only, then validate.py
    ~/.venvs/goldfish-cad/bin/python v01/build.py --fresh    # every step, no checkpoints: a release build
    ~/.venvs/goldfish-cad/bin/python v01/build.py --site     # also rebuild the site (local and deploy folder)
    ~/.venvs/goldfish-cad/bin/python v01/build.py --dry-run  # say what is stale and stop

A step is stale when a file it reads changed since it last ran (cad/stamps.py lists them). The enclosure
resumes from its last unchanged section (cad/stages.py): a change near the end of pebble_enclosure.py
rebuilds in about a minute instead of four.
"""
from __future__ import annotations

import subprocess
import sys
import time
from pathlib import Path

HERE = Path(__file__).parent
sys.path.insert(0, str(HERE / "cad"))
import stamps  # noqa: E402

PY = sys.executable


def main(argv):
    fresh, dry = "--fresh" in argv, "--dry-run" in argv
    st = stamps.stale()
    if dry:
        print("stale:", st or "nothing")
        return 0
    for step, script in stamps.SCRIPTS.items():
        st = stamps.stale()                    # re-read: a step that ran makes the next one stale
        if not fresh and step not in st:
            print(f"{step:10s} up to date")
            continue
        why = "--fresh" if fresh else ", ".join(st[step][:4])
        print(f"{step:10s} running ({why})", flush=True)
        t0 = time.time()
        cmd = [PY, script] + (["--fresh"] if fresh and step == "enclosure" else [])
        r = subprocess.run(cmd, cwd=HERE / "cad")
        if r.returncode:
            print(f"{step} failed (exit {r.returncode})")
            return r.returncode
        print(f"{step:10s} done in {time.time() - t0:.0f} s", flush=True)
    r = subprocess.run([PY, str(HERE / "validate.py")])
    if "--site" in argv and r.returncode == 0:
        for extra in ([], ["--web"]):
            subprocess.run([sys.executable, str(HERE.parent / "site" / "build.py"), *extra], check=True)
    return r.returncode


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
