#!/usr/bin/env python

import os
import sys
import argparse
import logging
import signal
import warnings
from pathlib import Path

from Gaudi import Configuration

from k4FWCore.utils import load_file, get_logger, set_log_level, LOG_LEVELS

# Terminate the process if a SIGPIPE is received
signal.signal(signal.SIGPIPE, signal.SIG_DFL)

# these default properties are filtered as otherwise they will clutter the argument list
FILTER_GAUDI_PROPS = [
    "Cardinality",
    "Context",
    "CounterList",
    "EfficiencyRowFormat",
    "Enable",
    "ErrorCount",
    "ErrorMax",
    "ErrorsPrint",
    "ExtraInputs",
    "ExtraOutputs",
    "FilterCircularDependencies",
    "MonitorService",
    "NeededResources",
    "PropertiesPrint",
    "RegisterForContextService",
    "RequireObjects",
    "RootInTES",
    "StatPrint",
    "StatTableHeader",
    "Timeline",
    "UseEfficiencyRowFormat",
    "EnableFaultHandler",
    "InhibitPathes",
    "EnableAccessHandler",
    "ForceLeaves",
    "RootName",
    "DataAccessName",
    "DataFaultName",
    "RootCLID",
    "Blocking",
    "VetoObjects",
    "CheckToolDeps",
    "AutoRetrieveTools",
]


def str_to_bool(value):
    """
    Parse a boolean command line value

    argparse's type=bool would turn any non-empty string (including "False")
    into True, so only accept explicit spellings and reject everything else
    """
    if isinstance(value, bool):
        return value
    lowered = value.strip().lower()
    if lowered == "true":
        return True
    if lowered == "false":
        return False
    raise argparse.ArgumentTypeError(
        f"invalid boolean value: '{value}' (use True/False or true/false)"
    )


def add_arguments(parser, app_mgr):
    """
    Add arguments to the parser for all properties of all configurables in the application manager

    :param parser: the parser to add the arguments to
    :param app_mgr: the application manager to get the properties from

    :return: a dictionary mapping the argument name to the configurable it belongs to

    Iterate over all the properties of all configurables in the application manager and add them to the parser.
    The property name is used as the argument name (twice) and the property value as the default value.
    If the property is a list, the type of the first element is used as the type of the argument.

    """

    option_db = {}

    # length increases when properties of an algorithm with tools are inspected
    # see https://github.com/key4hep/k4FWCore/pull/138
    # can contain the same value multiple times
    # see https://github.com/key4hep/k4FWCore/issues/141
    for conf in frozenset(app_mgr.allConfigurables.values()):
        # ToolSvcs will have their properties duplicated, once as the
        # named service itself and another one as "ToolSvc" if it's not
        # excluded here
        if any(name in conf.name() for name in ["ApplicationMgr", "ToolSvc"]):
            continue
        for prop_name, prop_value in conf.getPropertiesWithDescription().items():
            if (
                prop_name in FILTER_GAUDI_PROPS
                or "Audit" in prop_name
                or hasattr(prop_value[0], "__slots__")
            ):
                continue
            value = prop_value[0]

            # if it is set to "no value" it hasn't been touched in the options file
            if value == conf.propertyNoValue:
                value = conf.getDefaultProperty(prop_name)
            proptype = type(prop_value[0])
            args = "?"
            if proptype is list:
                if value:
                    proptype = type(value[0])
                # If the list is empty, we can't determine the type
                # Assume it's a string by default and hope it will work
                else:
                    proptype = str
                args = "+"
            extra_kwargs = {}
            # Properties not set in the options file hold propertyNoValue (a
            # string), so look at the default value as well to detect booleans
            if proptype is bool or isinstance(value, bool):
                proptype = str_to_bool
                # a bare flag (e.g. "--MetadataSvc.SkipIfSameValue") means True
                if args == "?":
                    extra_kwargs["const"] = True

            # add the argument twice, once as "--PodioOutput.filename"
            # and once as "--filename.PodioOutput"
            propName = f"{conf.name()}.{prop_name}"
            propNameReversed = f"{prop_name}.{conf.name()}"
            option_db[propName] = conf
            parser.add_argument(
                f"--{propName}",
                f"--{propNameReversed}",
                type=proptype,
                help=prop_value[1]
                .replace("%", "%%")  # Python 3.14 complains about single '%' in help strings
                .strip(),
                nargs=args,
                default=value,
                **extra_kwargs,
            )
    return option_db


def startInteractive(vars):
    """Start an interactive session"""
    import code

    # collect all global and local variables
    vars = vars.copy()

    # start the interpreter
    code.interact(
        local=vars,
        banner="Starting interactive Python session.  Exit with Ctrl-D to resume the job.",
    )
    return


def main():
    # ensure that we (and the subprocesses) use the C standard localization
    os.environ["LC_ALL"] = "C"

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter("[k4run - %(levelname)s] %(module)s.%(funcName)s: %(message)s")
    logger.handlers[0].setFormatter(formatter)

    from k4FWCore.parseArgs import parser

    parser.add_argument(
        "config_files",
        type=Path,
        action="store",
        nargs="*",
        help="Gaudi config (python) files describing the job",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Do not actually run the job, just parse the config files",
    )
    parser.add_argument(
        "-n",
        "--num-events",
        "--evt-max",
        type=int,
        help="Number of events to run (default: -1)",
    )
    parser.add_argument(
        "-l",
        "--list",
        action="store_true",
        help="Print all the configurable components available in the framework and exit",
    )
    parser.add_argument("--gdb", action="store_true", help="Attach gdb debugger")
    parser.add_argument(
        "--interactive-root",
        action="store_true",
        help="Run with ROOT in interactive mode (e.g. to see plots)",
        default=False,
    )
    parser.add_argument(
        "--log-level",
        help="Set the log (output) level for python and the ApplicationMgr",
        default=None,
        type=lambda x: x.upper(),
        choices=LOG_LEVELS,
    )

    parser.add_argument(
        "-i",
        "--interactive",
        action="store_true",
        help="Start a Python command loop after reading the configuration files",
        default=False,
    )

    # Once to parse the files and another time below to have the new parameters
    # in the namespace since parsing of the file happens when the namespace
    # has already been filled
    opts = parser.parse_known_args()
    logger = get_logger()
    set_log_level(opts[0].log_level or "INFO")

    if opts[0].list:
        cfgdb = Configuration.cfgDb
        logger.info("Available components:\n")
        for item in sorted(cfgdb):
            try:
                path_to_component = __import__(cfgdb[item]["module"]).__file__
            except ImportError:
                path_to_component = "NotFound"
            print(f"{item} (from {cfgdb[item]['lib']}), path: {path_to_component}")
        sys.exit()

    config_ns = {}
    for file in opts[0].config_files:
        config_ns.update(load_file(file))

    from Configurables import ApplicationMgr

    option_db = add_arguments(parser, ApplicationMgr())

    # add help manually here, if it is added earlier the parser exits after the first parse_arguments call
    parser.add_argument(
        "-h",
        "--help",
        action="help",
        default=argparse.SUPPRESS,
        help="show this help message and exit",
    )

    opts = parser.parse_args()

    if len(opts.config_files) == 0:
        print(
            "Error: missing gaudi options file.\n"
            "Usage: k4run <options_file.py>, use --help to get a complete list of arguments"
        )
        sys.exit(1)

    # print a doc line showing the configured algorithms
    logger.info(" ".join(f"--> {alg.name()}" for alg in ApplicationMgr().TopAlg))

    opts_dict = vars(opts)
    for optionName, conf in option_db.items():
        logger.info(f"Option name: {optionName} {opts_dict[optionName]}")
        # After Gaudi v39 the new configurable histograms have properties that are tuples
        # and by default one of the member is an empty tuple that Gaudi seems not to like
        # when used in setProp - it will try to parse it as a string and fail
        if "_Axis" in optionName:
            conf.setProp(
                optionName.rsplit(".", 1)[1], tuple(x for x in opts_dict[optionName] if x != ())
            )
        else:
            conf.setProp(optionName.rsplit(".", 1)[1], opts_dict[optionName])

    if opts.log_level:
        try:
            ApplicationMgr().OutputLevel = getattr(
                Configuration, logging.getLevelName(logger.level)
            )
        except AttributeError:
            logger.warning(
                f"{logging.getLevelName(logger.level)} (from log level {logger.level}) is not a valid OutputLevel for Gaudi"
            )

    if opts.num_events is not None:
        ApplicationMgr().EvtMax = opts.num_events
    # Allow graceful exit with Ctrl + C
    ApplicationMgr().StopOnSignal = True

    # Apply fixes from the k4FWCore wrapper

    from k4FWCore import ApplicationMgr

    ApplicationMgr().fix_properties(opts.log_level == "VERBOSE")

    from Gaudi.Main import gaudimain

    if opts.interactive:
        startInteractive(config_ns)

    gaudi = gaudimain()
    if not opts.dry_run:
        if not opts.interactive_root:
            os.environ.pop("DISPLAY", None)

        # Do the real processing
        retcode = gaudi.run(opts.gdb)
        # User requested stop returns non-zero exit code, see https://github.com/key4hep/k4FWCore/issues/125
        if retcode == 4:
            retcode = 0
        sys.exit(retcode)


if __name__ == "__main__":
    main()
