#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Checks that each aggregated projectcount file is current

Usage: check_validity_aggregated_projectcounts --data DATA_DIR
           [-v ...] [--help]

Options:
    -h, --help          Show this help message and exit
    --data DATA_DIR     Directory holding the csvs to check
    -v, --verbose       Increase verbosity
"""

# Add parent directory to python path to allow allow loading of modules without
# messing PYTHONPATH on the command line
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from docopt import docopt

import logging

import aggregator

if __name__ == '__main__':
    arguments = docopt(__doc__)

    # Setting up logging
    log_level_map = {
        1: logging.WARNING,
        2: logging.INFO,
        3: logging.DEBUG,
        }
    verbosity = min(arguments['--verbose'], 3)  # cap at 3, to allow many "-v"s
    log_level = log_level_map.get(verbosity, logging.ERROR)
    logging.basicConfig(level=log_level,
                        format='%(asctime)s %(levelname)-6s %(message)s',
                        datefmt='%Y-%m-%dT%H:%M:%S')

    logging.debug("Parsed arguments: %s" % (arguments))

    # Setting up directories
    data_dir_abs = arguments['--data']
    try:
        data_dir_abs = aggregator.existing_dir_abs(data_dir_abs)
    except ValueError:
        logging.error("Data directory '%s' does not point to an existing "
                      "directory" % (data_dir_abs))
        sys.exit(1)

    issues = aggregator.get_validity_issues_for_aggregated_projectcounts(
        data_dir_abs)

    if issues:
        for issue in issues:
            logging.error(issue)
        sys.exit(1)
