import pandas as pd
from sequana import snaketools as sm

sm.init("pacbio_denovo.rules", globals())

configfile: "config.yaml"
__snakefile__ = srcdir(__snakefile__)

# generic means do not use/set the read_tag
manager = sm.PipelineManager("pacbio_denovo", config)


# Starting of the pipeline
__rawdata__input = manager.getrawdata()
expected_output = []

# >>> manager.getname("canu")
# {sample}/canu/{sample}
#
# >>> pm.sample
# {sample}
#
# >>> pm.getwkdir("canu")
# {sample}/canu
#

__canu__input = __rawdata__input
__canu__output = manager.getname("canu") + ".contigs.fasta"
__canu__workdir = manager.getwkdir("canu")
__canu__log = manager.getlogdir("canu")
__canu__prefix = manager.sample
include: sm.modules["canu"]
#expected_output.append(expand(__canu__output, sample=manager.samples))


__busco__input = __canu__output
__busco__output = manager.sample + "/busco/run_" + manager.sample + "/full_table_{sample}.tsv"
__busco__workdir = manager.getwkdir("busco")
__busco__log = manager.getlogdir("busco")
include: sm.modules["busco"]
expected_output.append(expand(__busco__output, sample=manager.samples))

__busco_analysis__input = __busco__output
#__busco_analysis__output_filename = "report/busco/scores.csv"
__busco_analysis__output_pie = manager.getname("busco_analysis") + "_busco_pie.png"
__busco_analysis__output_scatter = manager.getname("busco_analysis") + "_busco_scatter.png"
include: sm.modules["busco_analysis"]
expected_output.append(expand(__busco_analysis__output_pie, sample=manager.samples))
expected_output.append(expand(__busco_analysis__output_scatter, sample=manager.samples))


__busco_scores__output = "report/busco_scores.csv"
rule busco_scores:
    input: expand(__busco_analysis__input, sample=manager.samples)
    output: __busco_scores__output
    run:
        from sequana.assembly import BUSCO
        scores = [BUSCO(x).score for x in input]
        df = pd.DataFrame([[x.split(os.sep)[-1] for x in input], scores], columns=['file', 'score'])
        df.to_csv(output[0])
expected_output.append(__busco_scores__output)


__rulegraph__input = __snakefile__
__rulegraph__output = "rulegraph/rulegraph.svg"
__rulegraph__mapper = {}
include: sm.modules['rulegraph']
expected_output.extend([__rulegraph__output])


# Add Conda
__conda__output = "requirements.txt"
include: sm.modules['conda']   # Create requirements.txt(dependencies)
expected_output.extend([__conda__output])


rule pacbio_denovo:
    input: expected_output


onsuccess:
    shell("multiqc . -f -m busco")
