from pathlib import Path

rule all:
    input:
        "output4.txt"

rule basic:
    """
    Here is some documentation.

    :input: A file
    :output: Another file
    :config length: Used to set params
    :param a: Set to config ``length`` value
    :param b: Sets the value of ``b``
    """

    input:
        "input.txt"
    output:
        report("output.txt")
    conda:
        "envs/test1.yaml"
    params:
        a=config["length"],
        b=3
    shell:
        "cat {input} > {output} && echo {params.a} >> {output}"

rule follows_basic:
    """
    Docs rhymes with socks...

    :config omega_m: mass density
    :config galaxy.stellar_mass: the galaxy stellar mass
    :config length: some random length
    """

    input:
        "output.txt"
    output:
        "output2.txt"
    resources:
        mem_mb=2
    params:
        stellar_mass=config["galaxy"]["stellar_mass"],
        length=config["length"]
    shell:
        "echo 'galaxy.stellar_mass = {params.stellar_mass}\n\noutput.txt content = ' > {output} && cat {input} >> {output}"

rule also_follows_basic:
    """
    Docs rhymes with fox...

    :config omega_m: mass density
    :config galaxy.stellar_mass: the galaxy stellar mass
    """

    input:
        "output.txt"
    output:
        "output3.txt"
    params:
        stellar_mass=config["galaxy"]["stellar_mass"]
    shell:
        "touch {output} && echo {params.stellar_mass}"

checkpoint gen_random:
    """
    Generates a random number (between 1 and 3) of empty files.

    :config conf1: a config var
    """

    input:
        rules.also_follows_basic.output
    output:
        directory("random")
    shell:
        """
        mkdir {output}
        for ii in $(seq 1 $(( $RANDOM % 3 + 1 ))); do
            touch {output}/$ii.tmp
        done
        """

def random_files(wildcards):
    checkpoints.gen_random.get()
    return list(Path("random").glob("*.tmp"))

rule the_end:
    input:
        random_files
    output:
        "output4.txt"
    shell:
        "echo {input} > {output}"
