from glob import glob

def get_create_pg_fasta_output_files(wildcards):
    checkpoint_output_dir = checkpoints.create_pg_fasta.get().output[0]
    return glob(os.path.join(checkpoint_output_dir, 'pg.*.faa'))


rule mafft_input_to_file:
    input:
        fastas=get_create_pg_fasta_output_files
    output:
        temporary('algn/pgs_to_align.txt')
    run:
        with open(output[0],'w') as out:
            for f in input.get("fastas", []):
                out.write(f + '\n')

rule run_mafft:
    input:
        'algn/pgs_to_align.txt'
    output:
        directory("algn/algn")  # '/pg.{i}.mafft'
    message:
        "aligning protein group members..."
    conda:
        "../../envs/mafft.yaml"
    shell:
        '''
        mkdir -p {output[0]}
        while read file; do
            pgID="$(basename ""$file"" | grep -o '[0-9]\\+')";
            mafft --auto --quiet --anysymbol --thread {threads} $file > {output[0]}/pg.${{pgID}}.mafft;
        done <{input[0]}
        '''
