import argparse
import sys

from . import __version__
from .core import draw, slice as slice_cucumber
from .errors import KheeraError


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Kheera CLI")
    parser.add_argument("--draw", action="store_true", help="Draw cucumber")
    parser.add_argument("--slice", type=int, help="Slice cucumber into N pieces")
    parser.add_argument("--version", action="store_true", help="Print version and exit")
    return parser


def main(argv=None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)

    if args.version:
        print(__version__)
        return 0

    try:
        if args.draw:
            draw()
        if args.slice is not None:
            slices = slice_cucumber(args.slice)
            print("\n".join(slices))
    except KheeraError as exc:
        print(f"{exc}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
