import os
import pandas as pd
import sys
from pling.utils import get_pling_root_dir, get_fasta_file_info, get_number_of_batches

configfile: "../config.yaml"

FASTAFILES, FASTAEXT, FASTAPATH = get_fasta_file_info(config["genomes_list"])
GENOMES = list(FASTAEXT.keys())
OUTPUTPATH = config["output_dir"] #output directory will contain subdirectory with unimogs from integerisation pipeline, as well as placing all new output from current pipeline in subdirectories within it
PREFIX = config["prefix"]
INTEGERISATION = config["integerisation"]
CONTAINMENT_DISTANCE = config["seq_containment_distance"]
COMMUNITIES = config["communities"]
batch_size = config["batch_size"]
dcj_threshold = config["dcj_dist_threshold"]

def get_timelimit(timelimit):
    if config["timelimit"]=="None":
        return ""
    else:
        return f"--timelimit {timelimit}"

rule all:
    input:
        dcj_graph_outdir = f"{OUTPUTPATH}/dcj_thresh_{dcj_threshold}_graph"

if config["ilp_solver"] == "GLPK":
    rule glpk_and_ding:
        input:
            containment_tsv = lambda wildcards: f"{OUTPUTPATH}/tmp_files/containment_batchwise/batch_{wildcards.batch}_containment.tsv"
        output:
            f"{OUTPUTPATH}/tmp_files/dists_batchwise/batch_{{batch}}_dcj.tsv"
        params:
            containment_distance=CONTAINMENT_DISTANCE,
            integerisation=INTEGERISATION,
            outputpath=OUTPUTPATH,
            communitypath=f"{COMMUNITIES}/objects/communities.txt",
            batch=lambda wildcards: wildcards.batch,
            timelimit=get_timelimit(config["timelimit"]),
            snakefile_dir=os.path.dirname(sys.argv[sys.argv.index("--snakefile")+1]),
            pling_root_dir = get_pling_root_dir()
        threads: 1 #no multithreading available for GLPK
        resources:
            mem_mb = lambda wildcards, attempt: attempt * config["ilp_mem"]
        conda: "../envs/ding_and_glpk.yaml"
        shadow: "shallow"
        shell:
                """
                PYTHONPATH={params.pling_root_dir} /opt/gensoft/exe/pling/1.0.3/venv/bin/python3.8  {params.pling_root_dir}/pling/dcj_snakemake/glpk_and_ding.py \
                        --batch {params.batch} \
                        --containment_tsv {input.containment_tsv} \
                        --containment_distance {params.containment_distance} \
                        --outputpath {params.outputpath} \
                        --communitypath {params.communitypath} \
                        --integerisation {params.integerisation} \
                        {params.timelimit} \
                        --threads {threads} \
                        --snakefile_dir {params.snakefile_dir}
                """

elif config["ilp_solver"] == "gurobi":
    rule gurobi_and_ding:
        input:
            containment_tsv = lambda wildcards: f"{OUTPUTPATH}/tmp_files/containment_batchwise/batch_{wildcards.batch}_containment.tsv"
        output:
            f"{OUTPUTPATH}/tmp_files/dists_batchwise/batch_{{batch}}_dcj.tsv"
        params:
            containment_distance=CONTAINMENT_DISTANCE,
            integerisation=INTEGERISATION,
            outputpath=OUTPUTPATH,
            communitypath=f"{COMMUNITIES}/objects/communities.txt",
            batch=lambda wildcards: wildcards.batch,
            timelimit=get_timelimit(config["timelimit"]),
            pling_root_dir = get_pling_root_dir()
        threads: config["ilp_threads"]
        resources:
            mem_mb = lambda wildcards, attempt: attempt * config["ilp_mem"]
        conda: "../envs/ding_and_glpk.yaml"
        shadow: "shallow"
        shell:
                """
                PYTHONPATH={params.pling_root_dir} /opt/gensoft/exe/pling/1.0.3/venv/bin/python3.8  {params.pling_root_dir}/pling/dcj_snakemake/gurobi_and_ding.py \
                        --batch {params.batch} \
                        --containment_tsv {input.containment_tsv} \
                        --containment_distance {params.containment_distance} \
                        --outputpath {params.outputpath} \
                        --communitypath {params.communitypath} \
                        --integerisation {params.integerisation} \
                        {params.timelimit} \
                        --threads {threads} \
                """
else:
    raise Exception("Not a valid ILP solver!")

rule dcj_tsv:
    input:
        dists = expand(f"{OUTPUTPATH}/tmp_files/dists_batchwise/batch_{{batch}}_dcj.tsv", batch=[str(i) for i in range(get_number_of_batches(OUTPUTPATH))])
    output:
        tsv = f"{OUTPUTPATH}/{PREFIX}_distances.tsv"
    threads: 1
    resources:
        mem_mb=lambda wildcards, attempt: 4000*attempt
    shell:
        """
        cat <(echo -e "plasmid_1\tplasmid_2\tdistance") {input.dists}> {output.tsv}
        """

rule build_DCJ_graph:
    input:
        distances_tsv = rules.dcj_tsv.output.tsv,
        communities=COMMUNITIES+"/objects/communities.pkl"
    output:
        dcj_graph_outdir = directory(f"{OUTPUTPATH}/dcj_thresh_{dcj_threshold}_graph")
    threads: 1
    resources:
        mem_mb=lambda wildcards, attempt: config["build_DCJ_graph_mem"]*attempt
    conda: "../envs/plasnet.yaml"
    params:
        dcj_dist_threshold=config["dcj_dist_threshold"],
        small_subcommunity_size_threshold = config["small_subcommunity_size_threshold"] #Communities with size up to this parameter will be joined to neighbouring larger subcommunities
    shell: """
            plasnet type \
                --distance-threshold {params.dcj_dist_threshold} \
                --small-subcommunity-size-threshold {params.small_subcommunity_size_threshold} \
                {input.communities} \
                {input.distances_tsv} \
                {output.dcj_graph_outdir}
        """
