from multiphasepy import case
from multiphasepy import workflow as mpyworkflow
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 = []
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 src_case_is_template(wildcards) -> bool:
    src_path = Path(wildcards.path.replace(target_dir, "."))
    if Path(src_path.parent, "caseParameterTable.ecsv").is_file():
        return True
    else:
        return False


def get_original_number_of_cores(wildcards) -> int:
    src_path = Path(wildcards.path.replace(target_dir, "."))
    if src_case_is_template(wildcards):
        foam_case = case.FoamBaseCase(src_path.parent)
    else:
        foam_case = case.FoamBaseCase(src_path)

    try:
        decomposeParDict = foam_case.get_dictionary("system/decomposeParDict")
        return int(decomposeParDict["numberOfSubdomains"])
    except:
        return 1


def get_original_number_of_threads(wildcards) -> int:
    return get_original_number_of_cores(wildcards)*threads_per_core()


def get_number_of_cores(wildcards, threads, resources) -> int:
    if workflow.remote_exec == True:
        return resources.tasks
    else:
        return threads//threads_per_core()

def category(wildcards) -> str:
    if src_case_is_template(wildcards):
        return str(Path(wildcards.path).parent)
    else:
        return subcategory(wildcards)


def subcategory(wildcards) -> str:
    if src_case_is_template(wildcards):
        return str(Path(wildcards.path).name)
    else:
        return wildcards.path


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


# Rule for initialising a case, i.e. copying it into the target "run" directory
rule init_case:
    output:
        "{path}/log.init",
    threads: threads_per_core()
    resources:
        tasks=1
    container: False
    params:
        subcategory=subcategory,
        is_template=src_case_is_template,
        target_dir=target_dir,
    script:
        "scripts/init.py"


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


# Rule for running a case
rule Allrun_case:
    input:
        "{path}/log.init"
    output:
        "{path}/log.Allrun",
        report
        (
            directory("{path}/postProcessing/report"),
            patterns=["{name}.png"],
            category=category,
            subcategory=subcategory
        )
    resources:
        tasks=get_original_number_of_cores
    threads: get_original_number_of_threads
    params:
        cores=get_number_of_cores
    shell:
        """
            workflow/scripts/Allrun.sh "$(dirname {output[0]})" \
                "{params.cores}" "{config[single_timestep]}"
        """


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


# Rule for validating results of a case
rule Allvalidate_case:
    output:
        "{path}/log.Allvalidate"
    threads: threads_per_core()
    resources:
        tasks=1
    shell:
        """
            workflow/scripts/Allvalidate.sh "$(dirname {output[0]})"
        """


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


# Rule for updating reference results of a case
rule Allupdate_case:
    output:
        "{path}/log.Allupdate"
    threads: threads_per_core()
    resources:
        tasks=1
    params:
        target_dir=target_dir,
    shell:
        """
            workflow/scripts/Allupdate.sh "$(dirname {output[0]})" \
                "{params[target_dir]}"
        """


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


# Rule for cleaning a case
rule Allclean_case:
    output:
        "{path}/log.Allclean"
    threads: threads_per_core()
    resources:
        tasks=1
    shell:
        """
            workflow/scripts/Allclean.sh "$(dirname {output[0]})"
        """

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


# Rule for running custom command for a case
rule custom_command_case:
    output:
        "{path}/log.custom_command"
    threads: threads_per_core()
    resources:
        tasks=1
    shell:
        """
            workflow/scripts/custom_command.sh "$(dirname {output[0]})" \
                "{config[custom_command]}"
        """


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