# Check version of snakemake
from snakemake.utils import min_version
min_version("9.5.0")

# Check installation of multiphasepy
try:
    from multiphasepy import case, workflow as mpyworkflow
except ImportError:
    logger.error("Module 'multiphasepy' is not installed. Depending on what "
                 + "you have access to see, install with recommended "
                 + "dependencies from: "
                 + "https://codebase.helmholtz.cloud/fwdc/python "
                 + "or https://doi.org/10.14278/rodare.3093")
    exit(1)


# Check version of multiphasepy
try:
    from multiphasepy import minimum_version
    minimum_version("2.0.0")
except RuntimeError as error:
    logger.error(error)
    exit(1)


import psutil


# Workflow configuration file to be edited by the user
configfile: "workflow.yml"


# Additional configuration
if "single_timestep" not in config:
    config["single_timestep"] = False

if "container" in config:
    container: config["container"]

if "custom_command" in config:
    custom_command: config["custom_command"]


# Workflow report description
report: "reports/report.rst"


# Current working directory
cwd = Path.cwd()


# Directory for running cases
target_dir = config["target_dir"]


# Case paths
paths = []

if config["include"] is None:
    (" to the 'include' field must not be empty or null")
    raise ValueError("Please add cases to be processed by the workflow to the "
                 + "`include` dictionary of `workflow.yml`. Consider using the "
                 + "`mpycollect` utility: `mpycollect --help`")

mpyworkflow.dicttoclist(d=config["include"], p=target_dir, plist=paths)


def threads_per_core() -> int:
    if workflow.cores == psutil.cpu_count(logical=True):
        logical_cores = psutil.cpu_count(logical=True)
        physical_cores = psutil.cpu_count(logical=False)
        return int(logical_cores/physical_cores)
    else:
        return 1

def get_number_of_cores(wildcards, threads) -> int:
    if workflow.remote_exec == True:
        return case.auto_select_case_type(wildcards.path).config_core()
    else:
        return threads//threads_per_core()

def report_category(wildcards) -> str:
    try:
        src_case = case.auto_select_case_type(
            Path(wildcards.path.replace(target_dir, ".")).parent
        )
        if src_case.is_templated():
            return src_case.path()
    except NotADirectoryError:
        return wildcards.path


def report_subcategory(wildcards) -> str:
    try:
        src_case = case.auto_select_case_type(
            Path(wildcards.path.replace(target_dir, ".")).parent
        )
        if src_case.is_templated():
            target_case = case.auto_select_case_type(wildcards.path)
            return target_case.name()
    except NotADirectoryError:
        return wildcards.path


# Global error messages upon success or failure of a workflow
onsuccess:
    logger.info("Workflow finished without errors.")
onerror:
    logger.error("Errors occurred. Run "
                 "`snakemake --summary -c 1 | grep missing` to get a list of "
                 "failed cases. Then check the corresponding log files.")


# Rule for initialising the workflow, i.e. copying the cases into the target
# "run" directory and creating Snakefiles
rule init:
    input:
        expand("{path}/.init", path=paths)


# Rule for initialising a case, i.e. copying it into the target "run" directory
rule init_case:
    output:
        "{path}/.init",
        report
        (
            directory("{path}/postProcessing/report"),
            patterns=["{name}.png"],
            category=report_category,
            subcategory=report_subcategory
        )
    log:
        "{path}/log.init"
    message:
        "Initializing case in {wildcards.path}"
    threads:
        threads_per_core()
    resources:
        cores=1
    container: False
    params:
        target_dir=target_dir,
    script:
        "scripts/init.py"


# Target rule for executing Allrun scripts of all cases
rule Allrun:
    input:
        expand("{path}/.Allrun", path=paths),
    default_target: True


# Rule for running a case
rule Allrun_case:
    input:
        "{path}/.init"
    output:
        "{path}/.Allrun"
    log:
        "{path}/log.Allrun"
    message:
        "Executing Allrun script in {wildcards.path}"
    resources:
        cores=get_number_of_cores
    threads:
        lambda wildcards: (
            case.auto_select_case_type(wildcards.path).config_core()
           *threads_per_core()
        )
    script:
        "scripts/Allrun.sh"


# Target rule for executing Allvalidate scripts of all cases
rule Allvalidate:
    input:
        expand("{path}/.Allvalidate", path=paths)


# Rule for validating results of a case
rule Allvalidate_case:
    output:
        "{path}/.Allvalidate"
    log:
        "{path}/log.Allvalidate"
    message:
        "Executing Allvalidate script in {wildcards.path}"
    threads:
        threads_per_core()
    resources:
        cores=1
    script:
        "scripts/Allvalidate.sh"


# Target rule for executing Allupdate scripts of all cases
rule Allupdate:
    input:
        expand("{path}/.Allupdate", path=paths)


# Rule for updating reference results of a case
rule Allupdate_case:
    output:
        "{path}/.Allupdate"
    log:
        "{path}/log.Allupdate"
    message:
        "Executing Allupdate script in {wildcards.path}"
    threads:
        threads_per_core()
    resources:
        cores=1
    params:
        target_dir=target_dir,
    script:
        "scripts/Allupdate.sh"


# Target rule for executing Allclean scripts of all cases
rule Allclean:
    input:
        expand("{path}/.Allclean", path=paths)


# Rule for cleaning a case
rule Allclean_case:
    output:
        "{path}/.Allclean"
    log:
        "{path}/log.Allclean"
    message:
        "Executing Allclean script in {wildcards.path}"
    threads:
        threads_per_core()
    resources:
        cores=1
    script:
        "scripts/Allclean.sh"

# Target rule for executing custom scripts of all cases
rule custom_command:
    input:
        expand("{path}/.custom_command", path=paths),


# Rule for running custom command for a case
rule custom_command_case:
    output:
        "{path}/.custom_command"
    log:
        "{path}/log.custom_command"
    message:
        (
            "Executing custom_command specified in workflow.yml script in"
            "{wildcards.path}"
        )
    threads: threads_per_core()
    resources:
        cores=1
    script:
        "scripts/custom_command.sh"


"""-------------------------------------------------------------------------"""
