# This subpipeline checks if the void report flag (.asscom2_void_report.flag) file has been modified by a rule in the parent pipeline. If so, the report will be rendered.

containerized: "docker://cmkobel/assemblycomparator2:v2.5.8" # Remember to copy the same version to the report_subpipeline/snakefile. I wonder if I can put this in the profile or config instead? 

__author__ = 'Carl M. Kobel'


results_directory = config['results_directory'] # results_ac2
base_variable = config['base_variable'] # path/to/gitrepo/assemblycomparator2
batch_title = config['batch_title'] # E.g. E._faecium 


print('report subpipeline: results_directory:', results_directory)
print('report subpipeline: base_variable:', base_variable)


try: 
    os.mkdir(f"{results_directory}/tables") # When using apptainer, I've had some problems with "mkdir: cannot create directory ‘/home/thylakoid/pnytera’: Read-only file system". I think moving this command out of the shell script may solve the problem?
except:
    pass


# The report should always run locally no matter the queuing system available.
localrules: report

rule all:
	input: expand(\
        "{results_directory}/report_{batch_title}.html", \
        results_directory = results_directory, batch_title = batch_title)


# Runs on the front end because it is quick anyway.
# This rule needs to be inside its own snakefile, as it is the only way I can run it on onerror/onsuccess
rule report:
    input:
        flag = "{results_directory}/.asscom2_void_report.flag", # This is the file being touched when void_report is called in every rule in the parent pipeline.
        metadata = "{results_directory}/metadata.tsv", # Without the metadata, the report doesn't make sense. Most segments use the metadata to translate sample names from files paths.
    conda: "conda_definitions/r-markdown.yaml"
    params: 
        base_variable = base_variable,
        results_directory = results_directory,
        batch_title = batch_title,
        end_script = f"{base_variable}/report_subpipeline/scripts/report_end_script.sh",
    output: 
        html = "{results_directory}/report_{batch_title}.html",
    #output: expand("{results_directory}/report_{batch_title}.html", results_directory = results_directory, batch_title = batch_title)
    
    shell: """


	    # When sharing environments by multiple users: Pandoc creates an intermediary .md file that reside next to the .Rmd file that is used to create the report. Because the directory where this .Rmd file resides may not be writable by the user that is executing the workflow. Thus, as a solution, we'll copy the whole script/ directory where this .Rmd resides to the current working directory.
        cp -r {base_variable}/report_subpipeline/scripts scripts_temporary # This one fails when using apptainer. Maybe I just need to bind it.
        

        #mkdir -p {params.results_directory}/tables  # Directory for the rmarkdown to write its compiled tables to.

        Rscript -e '
            base_variable = "{params.base_variable}"; results_directory = "{params.results_directory}"; batch_title = "{params.batch_title}"
            rmarkdown::render(
                input = "scripts_temporary/genomes_to_report_v3.Rmd",
                output_format = "html_document",
                output_file = "{output.html}",
                knit_root_dir = "{params.results_directory}",
            )'

        # Clean up 
        rm -r scripts_temporary

        # End script
        test -f "{params.end_script}" && echo "running end script" && . {params.end_script} {batch_title} {results_directory}/report_{batch_title}.html 
        
        
        # Create a zip archive of the report
        cd {results_directory} 
        zip -j {output.html}.zip {output.html} || echo failed to zip

        echo "report subpipeline: report written to {output.html}"
        echo "    ______________________________  "
        echo "   < The report has been rendered > "
        echo "    ------------------------------  "
        echo "           \\   ^__^                "
        echo "            \\  (oo)\\_______        "
        echo "               (__)\\       )\\/\\    "
        echo "                   ||----w |        "
        echo "                   ||     ||        "

    """









# Note: The stderr/out from rule report should not be shown on screen as it problematically wipes possible interesting fail-outputs from the main asscom2 pipeline.
