#!/usr/bin/env python3

import logging
import argparse
import dryable
from qcrepocleaner.Ccdb import Ccdb
from qcrepocleaner.binUtils import prepare_main_logger
import re


def parse_args():
    """Parse the arguments passed to the script."""
    logging.info("Parsing arguments")
    parser = argparse.ArgumentParser(description='Move all objects in path to new-path')
    parser.add_argument('--url', dest='url', action='store', help='URL of the CCDB, with http[s]://', required=True)
    parser.add_argument('--log-level', dest='log_level', action='store', default="20",
                        help='Log level (CRITICAL->50, ERROR->40, WARNING->30, INFO->20,DEBUG->10)')
    parser.add_argument('--dry-run', action='store_true',
                        help='Dry run, no actual deletion nor modification to the CCDB.')
    parser.add_argument('--path', dest='path', action='store', default="",
                        help='Origin path without initial slash and without .* at the end (e.g. qc/TST/MO/Bob).', required=True)
    parser.add_argument('--new-path', dest='new_path', action='store', default="",
                        help='New path without initial slash and without .* at the end (e.g. qc/TST2/MO/Bob).', required=True)
    parser.add_argument('--one-by-one', action='store_true', help='Ask confirmation for each deletion')
    parser.add_argument('--print-list', action='store_true', help='Only print the list of objects that would be deleted')
    args = parser.parse_args()
    dryable.set(args.dry_run)
    logging.info(args)
    return args


def run(args):
    ccdb = Ccdb(args.url)

    nb_moved = 0
    # we have to make sure we take all objects in the subfolders --> we add `/.*` at the end
    versions = ccdb.getVersionsList(args.path + "/.*", "", "")
    # we also want to have all the versions at the root
    versions += ccdb.getVersionsList(args.path, "", "")

    logging.info("Here are the objects that are going to be moved: ")
    for v in versions:
        logging.info(v)
    logging.info(f"Number of items: {len(versions)}")

    if args.print_list:
        exit(0)

    logging.warning("****** ARE YOU ABSOLUTELY SURE YOU WANT TO CONTINUE ? ******")
    answer = input("Yes/No \n  ")
    if answer.lower() not in ["y", "yes"]:
        exit(0)

    for v in versions:
        # here we need to make sure that we preserve the subdirectory structure and replace only the matching part
        version_new_path = re.sub("^" + args.path, args.new_path.rstrip('/'), v.path.rstrip('/'), count=0, flags=0)
        logging.info(f"Ready to move {v} to {version_new_path}")
        if args.one_by_one:
            answer = input("  Continue? y/n\n  ")
            if answer.lower() in ["y", "yes"]:
                ccdb.moveVersion(v, version_new_path)
                nb_moved += 1
            elif answer.lower() in ["n", "no"]:
                logging.info("   skipping")
            else:
                logging.error("   wrong input, skipping")
        else:
            ccdb.moveVersion(v, version_new_path)
            nb_moved += 1

    logging.info(f"Moved items: {nb_moved}")

# ****************
# We start here !
# ****************

def main():
    prepare_main_logger()

    # Parse arguments
    args = parse_args()
    logging.getLogger().setLevel(int(args.log_level))

    run(args)


if __name__ == "__main__":
    main()
