#! /usr/bin/env python3

"""
Check that the known dependencies of contur are accessible though no version
checking is currently enforced. The core dependencies are read from the
installed contur distribution's metadata rather than from a separate
requirements file. YODA and Rivet are checked by import, since they are not
trackable in pip.

Exit codes:
1 = not Python 3
2 = third-party dependency missing or broken
3 = analysis database not usable
4 = contur itself is missing or broken

"""

import importlib
import importlib.util
import os
import re
import sys
from importlib.metadata import PackageNotFoundError, requires

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 install_hint():
    contur_root = os.getenv("CONTUR_ROOT", "/path/to/contur")
    return "\n".join([
        "The 'contur' package is not installed in the current Python environment.",
        "Create and activate a virtual environment, then install contur in editable mode:",
        "  python3 -m venv .venv          # or: uv venv",
        "  source .venv/bin/activate",
        "  python -m pip install -e {root}    # or: uv pip install -e {root}".format(root=contur_root),
    ])


def check_py3():
    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 core_dependencies():
    """
    The non-optional runtime dependencies declared by the installed contur
    distribution. Requirements guarded by an 'extra ==' marker (e.g. spey,
    pymysql) are optional and skipped.
    """
    deps = []
    for req in requires("contur") or []:
        name_part, _, marker = req.partition(";")
        if re.search(r"extra\s*==", marker):
            continue
        match = re.match(r"[A-Za-z0-9][A-Za-z0-9._-]*", name_part.strip())
        if match:
            # normalise per PEP 503 so the name matches the module name overrides
            # regardless of the spelling in the distribution metadata
            deps.append(re.sub(r"[-_.]+", "-", match.group(0)).lower())
    return deps


def check_deps():
    anyFail = False

    try:
        core_deps = core_dependencies()
    except PackageNotFoundError:
        # contur may still be importable from the source tree (multiuser setups
        # source setupContur.sh without a pip install); the final import guard
        # reports a genuinely missing contur, so only note the reduced check here
        core_deps = []
        if importlib.util.find_spec("contur") is None:
            info("Cannot read contur's declared dependencies (contur is not installed); checking Rivet/YODA only.")
        else:
            info("contur is importable but not pip-installed (source-tree mode); skipping the declared-dependency check.")


    # distribution names whose import name differs
    module_name_overrides = {
        "pyyaml": "yaml",
        "scikit-learn": "sklearn",
    }

    pip_needed = []
    for pk in core_deps:
        mod = module_name_overrides.get(pk, pk.replace("-", "_"))
        try:
            i = importlib.import_module(mod)
            debug('Successfully found {} Python module'.format(pk))
        except ModuleNotFoundError as e:
            if e.name == mod:
                warning('{} Python module not found'.format(pk))
                pip_needed.append(pk)
            else:
                warning('{} Python module failed to import: {}'.format(pk, e))
            anyFail = True
        except Exception as e:
            # an installed dependency that is broken (e.g. an ABI mismatch)
            # needs the real error, not installation advice
            warning('{} Python module failed to import: {}'.format(pk, e))
            anyFail = True
    if anyFail:
        warning("\nOne or more Python dependencies was not found. Install them into the active virtual environment, e.g.")
        warning("  python -m pip install {}".format(" ".join(pip_needed)))

    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():
            sys.exit(1)
        deps_ok = check_deps()
    else:
        deps_ok = True

    # import contur before deciding the exit code and before check_DB, so that a
    # missing or broken contur is reported as such (exit 4) rather than as a
    # database failure swallowed by check_DB's blanket except
    try:
        import contur
    except ImportError as e:
        # distinguish contur not being installed from an installed contur that is
        # broken (e.g. a circular import, cf. issue #575) -- the latter needs the
        # real error, not installation advice
        if isinstance(e, ModuleNotFoundError) and e.name == "contur":
            warning(install_hint())
        else:
            warning(str(e))
            warning("The 'contur' package was found but failed to import; fix the error above before proceeding.")
        sys.exit(4)

    if not PRINTONLY:
        if not deps_ok:
            sys.exit(2)
        if not check_DB():
            sys.exit(3)
    msg = "Contur {v} environment successfully enabled".format(v=contur.__version__)
    info(len(msg) * "-")
    info(msg)
    info(len(msg) * "-")
