import os
from snakemake.utils import listfiles


rule report_mafft:
    input:
        rules.run_mafft.output
    output:
        directory("algn/report")  # 'mafft.{i}.txt'
    message:
        "checking pairwise identity of protein groups..."
    run:
        os.mkdir(output[0])
        for f, pg_no in listfiles(os.path.join(input[0],'pg.{n}.mafft')):
            seqs = []
            with open(f,"r") as handle:
                for line in handle:
                    line = line.strip()
                    if len(line) == 0:
                        continue
                    if line[0] == ">":
                        seqs.append([])
                    else:
                        seqs[-1].append(line)
            seqs = [''.join(x) for x in seqs]
            l = len(seqs[0])
            seqlens = [len(x.replace("-","")) for x in seqs]

            #calc relative pairwise identities
            idents = [l - sum(1 for y in zip(x[0],x[1]) if y[0] != y[1]) for x in itertools.combinations(seqs,2)]
            min_idents = round(min(idents) / l * 100,2)
            max_idents = round(max(idents) / l * 100,2)

            #write out
            with open(os.path.join(output[0],f'mafft.{pg_no}.txt'),"w") as handle:
                handle.write("#min_seqlen\tmax_seqlen\tmin_rel_pairw_ident\t#max_rel_pairw_ident\n")
                handle.write(str(min(seqlens)) + "\t" + str(max(seqlens)) + "\t" + str(min_idents) + "\t" + str(max_idents))
