###########################################
# Imports
###########################################

from scikick.config import read_deps, ScikickConfig, read_snakefile_arg
from scikick.utils import warn, get_sk_exe_dir
import tempfile

# capture the name of the log file
warn(f"SK INTERNAL: logfile {logger.logfile}")

# trying to eventually remove this
# configfile: 'scikick.yml'
# Instead of snakemake config file,
# import the scikick.yml config file directly.
skconfig=ScikickConfig()
config=skconfig.config

###########################################
# Workflow variables
###########################################

snakefile_args = dict()
for arg in ["singularity", "conda", "benchmark", "threads"]:
    snakefile_args[arg] = read_snakefile_arg(arg)
    if snakefile_args[arg] is None:
        if arg != "threads":
            snakefile_args[arg] = ""
        else:
            snakefile_args[arg] = 1

# Importing report_step basenames
analysis = skconfig.analysis

# directories
report_dir = skconfig.report_dir
# bin files
exe_dir=get_sk_exe_dir()
script_dir = os.path.join(exe_dir, "scripts")
template_dir = os.path.join(exe_dir, "template")
snake_src = os.path.join(exe_dir, "usr", "Snakefile")

data_parent = "output"

inner_ymls = [os.path.join(report_dir, "out_md", dir, "_site.yml")
	for dir in set([os.path.dirname(a) for a in analysis.keys()])]
###########################################
# Dependencies
###########################################
rmd_dict = {}
for key in analysis:
	rmd_dict[os.path.splitext(key)[0]] = key

rmd_deps = skconfig.inferred_deps

# add index if doesn't exist
sys_index = os.path.join(template_dir, 'index.Rmd')
index_list = list(filter(lambda f: os.path.basename(f) == "index", \
	rmd_dict.keys()))
#if 'index' not in rmd_dict.keys():
if len(index_list) != 1:
	warn("sk: Include an index.Rmd to add content " +\
		"to the required index.html page")
	rmd_dict['index'] = rmd_deps['index'] = sys_index
else:
	rmd_dict['index'] = rmd_dict.pop(os.path.splitext(index_list[0])[0], None)
	rmd_deps['index'] = rmd_deps.pop(os.path.splitext(index_list[0])[0], None)
index_rmd = rmd_dict["index"]
###########################################
# Workflow rules
###########################################

# Rules that should never require cluster execution
localrules: siteYAML, pageRender, AWdone

rule AWdone:
	input:
		expand('{report_dir}/out_html/{report_step}.html',
			report_step = list(rmd_dict.keys()), report_dir = report_dir)
	message: "All rules from {snake_src} are complete"

# TODO: specify this for rmd files only
rule reportRendering:
	input:
		deps = lambda wildcards: rmd_deps[wildcards.report_step],
		rmd = lambda wildcards: rmd_dict[wildcards.report_step]
	output:
		md = os.path.join(report_dir, "out_md", "{report_step}.md")
	message: "Executing R chunks in {input.rmd}, " + \
			"outputting to {output.md}"
	params:
		simplified_input = len("{input.rmd}"),
		data_parent = data_parent,
		template_dir = template_dir,
		script_dir = script_dir
	conda: snakefile_args["conda"]
	singularity: snakefile_args["singularity"]
	threads: int(snakefile_args["threads"])
	benchmark: snakefile_args["benchmark"] + "{report_step}" if snakefile_args["benchmark"] != "" else ""
	shell: "Rscript %s {input.rmd} {output.md} {params.template_dir} \
		{params.data_parent} {params.script_dir} {logger.logfile} \
		{index_rmd}" \
		% os.path.join(script_dir, "reportRendering.R")
# 'script:' section causes directories to not get found when using singularity, so 'shell:' is used

# Generate all _site.yml files
rule siteYAML:
	input: yaml = "scikick.yml"
	output:
		main_yml = os.path.join(report_dir, "out_md", "_site.yml"),
		inner_ymls = inner_ymls
	message: "Creating site layout from scikick.yml"
	script: os.path.join(script_dir, 'yamlgen.py')

# md => HTML via rmarkdown::render
rule pageRender:
	input:
		yaml = "{report_dir}/out_md/_site.yml",
		md = "{report_dir}/out_md/{report_step}.md"
	output:
		"{report_dir}/out_html/{report_step}.html"
	message: "Generating {report_dir}/out_html/{wildcards.report_step} html page"
	params:
		template_dir = template_dir,
		index_html = lambda w: os.path.join(os.path.relpath(
			os.path.join(report_dir, "out_md"),
			os.path.dirname(os.path.join(report_dir,
				"out_md", "%s.md" % w.report_step))), "index.html")
	conda: snakefile_args["conda"]
	singularity: snakefile_args["singularity"]
	shell: "Rscript %s {input.md} {output} {params.template_dir} {params.index_html}" \
		% os.path.join(script_dir, "render.R")
# using 'shell:' instead of 'script:' for compatibility with renv

user_snakefile = os.path.join(os.getcwd(), "Snakefile")
if os.path.isfile(user_snakefile):
	warn("sk: Using Snakefile found in working directory")
	include: user_snakefile
