#!/usr/bin/python3 -u
import logging as log
import os.path
import sys

cosa_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, f"{cosa_dir}/cosalib")
sys.path.insert(0, cosa_dir)

from cosalib.build import BuildExistsError
from cosalib.cli import BuildCli
import cosalib.qemuvariants as QVariants
import cosalib.ova as OVA


def METHOD_NAME(imgtype, build_root, build="latest", force=False, compress=False, schema=None):
    kargs = {
        "build": build,
        "buildroot": build_root,
        "force": force,
        "compress": compress,
        "schema": schema,
        "variant": imgtype
    }

    if imgtype in QVariants.VARIANTS:
        log.info(f"Target '{imgtype.upper()}' is a Qemu Variant image")
        return QVariants.QemuVariantImage(**kargs)

    if imgtype in OVA.VARIANTS:
        return OVA.OVA(**kargs)

    raise Exception(f"{imgtype} is not supported by this command")


def artifact_cli():
    """ cli implements command-line innovation """
    log.basicConfig(
        format='[%(levelname)s]: %(message)s',
        level=log.INFO)

    targets = list(QVariants.VARIANTS.keys())
    targets.extend(OVA.VARIANTS.keys())
    targets.append("manual")

    parser = BuildCli()
    subparsers = parser.add_subparsers(dest="command")

    # Options for finding the build.
    parser.add_argument("--force", action='store_true',
                        help="Force rebuild of existing disk")
    parser.add_argument("--compress", action='store_true',
                        help="Compress generated image")

    # Support for legacy cmd-buildextend-* targets
    symlink = None
    for k in targets:
        if sys.argv[0].endswith(f"cmd-buildextend-{k}"):
            symlink = k
            log.info(f"CLI is a symlink for cmd-buildextend-{k}")
            break

    # Predefined mode
    target = subparsers.add_parser(name="target",
                                   description="manually define build")
    target.add_argument("target", default=None,
                        help="name of predefined target",
                        choices=targets)

    # Manual mode for developers
    manual = subparsers.add_parser(name="manual",
                                   description="build new disk from cli args")
    manual.add_argument("--image_format", required=True,
                        help="qemu-img supported image format, i.e vpc")
    manual.add_argument("--image_suffix", required=True,
                        help="file name suffix")
    manual.add_argument("--platform", required=True,
                        help="Ignition platform to set image to")
    manual.add_argument("--convert_options",
                        help="qemu-img options")
    manual.add_argument("--virtual-size", help="Virtual Size to use")

    args = parser.parse_args()

    builder = None

    # Figure out if the build target has been set
    build_target = None
    if "target" in args:
        build_target = args.target
    elif symlink:
        build_target = symlink

    if build_target:
        builder = METHOD_NAME(build_target, args.buildroot, args.build,
                              force=args.force, compress=args.compress, schema=args.schema)
    elif args.command == "manual":
        kwargs = {
            'force': args.force,
            'image_format': args.image_format,
            'image_suffix': args.image_suffix,
            'platform': args.platform,
            'schema': args.schema,
            'virtual_size': args.virtual_size,
        }
        if args.convert_options:
            kwargs["convert_options"] = {'-o': f'{args.convert_options}'}

        builder = QVariants.QemuVariantImage(buildroot=args.buildroot,
                                             build=args.build,
                                             **kwargs)
    else:
        raise Exception("please see --help for correct invocation")

    return builder


if __name__ == '__main__':
    try:
        artifact_cli().build_artifacts()
    except BuildExistsError as e:
        log.warning(e)