#! /usr/bin/env python

'''
Normally one would use a setup.py script to check dependencies. This is not
used here, primarily since the core dependencies of YODA and Rivet Python
modules are not trackable in pip. Instead this script manually checks that the
known dependencies are at least accesible, no version checking is currently
enforced

'''

import importlib, os

VERBOSITY = 1
def log(msg, v):
    if v >= VERBOSITY:
        print(msg)
def debug(msg):
    log(msg, 0)
def info(msg):
    log(msg, 1)
def warning(msg):
    log(msg, 2)


def check_py3():
    import sys
    rtn = (sys.version_info.major == 3)
    if not rtn:
        warning("This release is designed for Python 3 installations, refer to https://hepcedar.gitlab.io/contur-webpage/ for Python 2 options")
    return rtn


def check_deps():
    anyFail = False

    reqfile = os.path.join(os.getenv("CONTUR_ROOT"),"requirements.in")

    pip_needed = []    
    with open(reqfile, 'r') as req:
        for line in req:
            line = line.split('>')[0]
            pk = line.strip()
            if pk == "pyyaml":
                # special case because the package name isn't the same as the module name
                mod = "yaml"
            elif pk == "scikit-learn":
                # special case because the package name isn't the same as the module name
                mod = "sklearn"
            else:
                mod = pk
                
            try:
                i = importlib.import_module(mod)
                debug('Successfully found {} Python module'.format(pk))
            except ImportError:
                warning('{} Python module not found'.format(pk))
                pip_needed.append(pk)
                anyFail = True
    if anyFail:
        warning("\nOne or more Python dependencies was not found. Try installing with pip, maybe in a venv, e.g.")
        warning("  python -m venv venv")
        warning("  source venv/bin/activate")
        warning("then")
        warning("  pip install {}".format(" ".join(pip_needed)))
        warning("or")
        warning("  pip install -r requirements.txt")

    try:
        import yoda
        debug('Successfully found YODA Python module')
    except ImportError:
        warning('yoda Python module not found, ensure a valid installation of Rivet/YODA has been set up')
        anyFail = True
        
    try:
        import rivet
        debug('Successfully found Rivet Python module')
    except ImportError:
        warning('rivet Python module not found, ensure a valid installation of Rivet has been set up.')
        anyFail = True

    if anyFail:
        warning("\nOne or more dependency checks failed, try to resolve before proceeding")
        return False

    debug("\nAll Python module dependencies appear to be accessible.")
    return True


def check_DB():
    try:
        import sys, contur
        from pathlib import Path
        import contur.database.static_db as cdb
        import contur.config.paths as cpaths
        
        dbfile = Path(cpaths.user_path('analyses.db'))
        if not dbfile.exists():
            raise Exception("{} not found.".format(dbfile))
        cdb.init_dbs()
    except Exception as e:
        print(e)
        warning("Failed to connect to analysis database, ensure that make has been successfully run.")
        return False
    return True


if __name__ == '__main__':
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument("-V", "--verbose", dest="VERBOSITY", action="store_const", const=0, default=1, help="print debug messages while running")
    ap.add_argument("-Q", "--quiet", dest="VERBOSITY", action="store_const", const=2, default=1, help="minimise messages while running")
    ap.add_argument("-P", "--printonly", dest="PRINTONLY", action="store_true", default=False, help="just load and print version")
    args = ap.parse_args()

    VERBOSITY = args.VERBOSITY
    PRINTONLY = args.PRINTONLY
    
    if not PRINTONLY:
        if not check_py3():
            exit(1)
        if not check_deps():
            exit(2)
        if not check_DB():
            exit(3)

    import contur
    msg = "Contur {v} environment successfully enabled".format(v=contur.__version__)
    info(len(msg) * "-")
    info(msg)
    info(len(msg) * "-")
