#!python

import logging
import argparse
import dryable
from qcrepocleaner.Ccdb import Ccdb, ObjectVersion
from qcrepocleaner.binUtils import prepare_main_logger
import csv


def parseArgs():
    """Parse the arguments passed to the script."""
    logging.info("Parsing arguments")
    parser = argparse.ArgumentParser(description='Remove all objects in a given path, if they dont belong to any of '
                                                 'the runs. The runs are provided in a csv file whose format is the '
                                                 'one from the bookkeeping export.')
    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='Clean this path (without initial slash and without .* at the end, e.g. qc/TST/MO/Bob)',
                        required=True)
    parser.add_argument('--runs-csv-file', dest='runs_file', action='store', help='A csv file with a header and the '
                                                                                  'column `runNumber` contains the run',
                        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)

    file = open(args.runs_file)
    csvreader = csv.DictReader(file)
    list_runs = []
    for row in csvreader:
        list_runs.append(row["runNumber"])
    logging.debug(f"List of runs in CSV: {list_runs}")

    versions = ccdb.getVersionsList(args.path + "/.*")
    nb_deleted = 0
    for v in versions:
        logging.debug(f"Processing {v}")
        run_number = v.metadata["RunNumber"]
        if run_number is not None and list_runs.count(run_number) == 0:
            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:
                if not args.print_list:
                    ccdb.deleteVersion(v)
                nb_deleted += 1

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


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

def main():

    prepare_main_logger()

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

    run(args)


if __name__ == "__main__":
    main()
