#!/usr/bin/env python3
"""Triage Design System — entry point.

    python3 build.py core                compose core/base.css + core/patterns.css
                                         from the canonical src/core/ sources
    python3 build.py tokens              regenerate tokens/tokens.css from tokens.json
    python3 build.py icons               regenerate icons/sprite.svg + icons/icons.json
    python3 build.py exports             regenerate exports/ for Figma / Tokens Studio / Style Dictionary
    python3 build.py check               run the full repo self-check (core sync, tokens, DTCG,
                                         rename sweep, spec catalogue, lint self-test)
    python3 build.py sync --force --pack PATH
                                         re-assemble core/ + examples/ from an external
                                         design pack (provenance maintenance; refused
                                         without --force because src/core/ is canonical)
"""
import os
import subprocess
import sys

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


def run(*cmd):
    print("+", " ".join(cmd))
    return subprocess.call(cmd, cwd=HERE)


def main(argv):
    if len(argv) < 2 or argv[1] in ("-h", "--help"):
        print(__doc__)
        return 0
    cmd = argv[1]
    if cmd == "core":
        return run(sys.executable, os.path.join(HERE, "tools", "build_core.py"), *argv[2:])
    if cmd == "tokens":
        return run(sys.executable, os.path.join(HERE, "tools", "build_tokens.py"))
    if cmd == "icons":
        return run(sys.executable, os.path.join(HERE, "tools", "build_icons.py"))
    if cmd == "exports":
        return run(sys.executable, os.path.join(HERE, "tools", "export_tokens.py"))
    if cmd == "check":
        rc = run(sys.executable, os.path.join(HERE, "tools", "build_core.py"), "--check")
        if rc:
            return rc
        rc = run(sys.executable, os.path.join(HERE, "tools", "verify.py"))
        if rc:
            return rc
        return run(sys.executable, "-m", "unittest", "discover", "-s",
                   os.path.join(HERE, "lint", "tests"), "-t", HERE, "-q")
    if cmd == "sync":
        if "--force" not in argv[2:]:
            print("refusing to sync without --force: src/core/ is canonical now.\n"
                  "`build.py sync` re-assembles core/ and tokens/ from an external design pack and is\n"
                  "provenance maintenance only. Edit src/core/** and run `python3 build.py core`\n"
                  "instead; `build.py sync --force` stages its output under dist/pack-sync/ and never\n"
                  "overwrites core/ or tokens/.")
            return 1
        return run(sys.executable, os.path.join(HERE, "tools", "assemble_from_pack.py"), *argv[2:])
    print("unknown command %r — see python3 build.py --help" % cmd)
    return 2


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