# Multiphase Python Repository by HZDR
#
# SPDX-FileCopyrightText: 2026 Helmholtz-Zentrum Dresden-Rossendorf e.V. (HZDR)
#
# SPDX-License-Identifier: GPL-3.0-or-later

# Check installation of multiphasepy

try:
    from multiphasepy import case, workflow as mpyworkflow
    from multiphasepy.exceptions import NotACaseError
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 for minimum required version of multiphasepy
try:
    from multiphasepy import minimum_version

    minimum_version("4.3.1")
except RuntimeError as error:
    logger.error(error)
    exit(1)

import os
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 "custom_command" in config:
    custom_command: config["custom_command"]

if "env_var" in config:
    for key, value in config["env_var"].items():
        os.environ[key] = str(value)


# 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 "
        + "`mpyworkflow collect` utility: "
        + "`mpyworkflow collect --help`"
    )

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


def get_container(wildcards):
    try:
        return case.auto_select_case_type(Path(wildcards.path)).config_container()
    except:
        return config.get("container", False)


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(Path(wildcards.path)).config_core()
    else:
        return threads // threads_per_core()



def get_case_software(wildcards) -> str:
    src_case = case.auto_select_case_type(Path(wildcards.path.replace(target_dir, ".")))
    software = src_case.simulation_software()
    return software


def get_license_server(wildcards) -> str:
    software = get_case_software(wildcards)
    return config["license_server"][software]


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 NotACaseError:
        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(Path(wildcards.path))
            return target_case.name()
    except NotACaseError:
        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 <rule, e.g. Allrun> | 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(Path(wildcards.path)).config_core()
            * threads_per_core()
        )
    container:
        get_container
    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,
    container:
        get_container
    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,
    container:
        get_container
    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,
    container:
        get_container
    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,
    container:
        get_container
    script:
        "scripts/custom_command.sh"


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