#!/usr/bin/env python3

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


def parse_args():
    """Parse the arguments passed to the script."""
    logging.info("Parsing arguments")
    parser = argparse.ArgumentParser(description='Delete all objects listed in file')
    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('--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')
    parser.add_argument('--objects-list-file', dest='objects_file', action='store', help='A text file with 1 object per '
                                                                                      'line', required=True)
    parser.add_argument('--yes', action='store_true', help='Answers yes to all. You should really not use that.')
    args = parser.parse_args()
    dryable.set(args.dry_run)
    logging.info(args)
    return args


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

    total_deleted = 0

    with open(args.objects_file, 'r') as file:
        # Loop over each line in the file
        for line in file:
            nb_deleted = 0

            # Print each line
            stripped_line = line.strip()
            if not stripped_line:
                continue
            logging.debug(f"line : '{stripped_line}'")

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

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

            if args.print_list or len(versions) == 0:
                continue

            if not args.yes:
                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:
                logging.info(f"Ready to delete {v}")
                if args.one_by_one:
                    answer = input("  Continue? y/n\n  ")
                    if answer.lower() in ["y", "yes"]:
                        ccdb.deleteVersion(v)
                        nb_deleted += 1
                    elif answer.lower() in ["n", "no"]:
                        logging.info("   skipping")
                    else:
                        logging.error("   wrong input, skipping")
                else:
                    ccdb.deleteVersion(v)
                    nb_deleted += 1

            logging.info(f"Deleted items: {nb_deleted}")
            total_deleted += nb_deleted

    logging.info(f"Total deleted items: {total_deleted}")

# ****************
# 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()
