# SPDX-License-Identifier: MIT

import argparse
import pathlib
import sys

import picobuild


def nothing_missing(missing):
    """
    If nothing is missing (the set is empty) then return True, otherwise print
    the missing dependencies and return False.
    """
    if not missing:
        return True

    print("Missing build dependencies:")
    deps = "\n".join("- " + d[0] for d in missing)
    print(deps)
    return False


def main(args=None) -> int:
    parser = argparse.ArgumentParser(
        prog="python3 -mpicobuild", description="Pico-sized Python Package Builder."
    )
    # TODO type validation
    parser.add_argument(
        "--source", "-s", default=".", help="Source directory containing pyproject.toml"
    )
    parser.add_argument(
        "--dest", "-d", default="dist", help="Destination directory for built files"
    )
    parser.add_argument("--sdist", "-t", action="store_true", help="Build a sdist")
    parser.add_argument("--wheel", "-w", action="store_true", help="Build a wheel")
    parser.add_argument(
        "--loose-depends", "-l", action="store_true", help="Loosen dependency checking"
    )
    # TODO config options

    args = parser.parse_args(args)
    args.dest = pathlib.Path(args.dest).resolve()
    args.options = None

    if not args.sdist and not args.wheel:
        print("No target (--sdist or --wheel) specified.")
        return 1

    builder = picobuild.Builder(args.source, args.loose_depends)

    if not nothing_missing(builder.check_bootstrap_dependencies()):
        return 1

    if args.sdist:
        if not nothing_missing(builder.check_sdist_dependencies(args.options)):
            return 1
        output = builder.build_sdist(args.dest, args.options)
        print(f"Wrote sdist {args.dest / output}")

    if args.wheel:
        if not nothing_missing(builder.check_wheel_dependencies(args.options)):
            return 1
        output = builder.build_wheel(args.dest, args.options)
        print(f"Wrote wheel {args.dest / output}")

    return 0


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