import argparse
import logging
import os
import sys
import traceback

from abl.installer import Updater, setup_assert
from abl.vpath.base import URI


logger = logging.getLogger("abl.installer")


def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    def error_assert(condition, message):  # pragma: no coverage
        if not condition():
            logger.error(message)
            sys.exit(1)

    setup_assert(error_assert)

    parser = argparse.ArgumentParser(description="Ableton Update Delta File Installer")

    parser.add_argument(
        "--loglevel", help="Loglevel, one of DEBUG, INFO, WARNING, ERROR", default="INFO"
    )
    parser.add_argument(
        "--log-file-path", dest="log_file_path", help="The file to log into"
    )

    parser.add_argument(
        "--from", help="path to the current version of Live", dest="from_", required=True
    )
    parser.add_argument(
        "--to",
        help="path where Live will be cloned to and the update applied",
        required=True,
    )
    parser.add_argument("--asu", help="path to the ASU file to apply", required=True)

    args = parser.parse_args(argv)

    logging_args = dict(
        level=getattr(logging, args.loglevel.upper()),
        format="%(levelname)s:%(asctime)s:%(name)s:%(message)s",
    )
    if args.log_file_path:
        logging_args["filename"] = args.log_file_path
    else:
        logging_args["stream"] = sys.stderr

    logging.basicConfig(**logging_args)

    try:
        logger.info(
            "Preparing to apply auto update from %s to %s using %s",
            args.from_,
            args.to,
            args.asu,
        )
        updater = Updater(
            URI(os.path.normpath(os.path.expanduser(args.from_))),
            URI(os.path.normpath(os.path.expanduser(args.to))),
            # apply_single_update() will extract the .asu file in a temporary directory
            # and won't use the "_autoupdates" folder, so we don't need to provide
            # "autoupdates_dir_base_path" here.
            None,
        )
        updater.apply_single_update(URI(os.path.normpath(os.path.expanduser(args.asu))))
    except:
        logger.error(
            traceback.format_exception(
                sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
            )
        )
        raise


if __name__ == "__main__":
    main()  # pragma: no cover
