import sys, os, math, json
absolute_dir = "/opt/mosga/snakemake/"
rules_dir = absolute_dir + "rules/"

include: rules_dir + "cores.smk"
include: rules_dir + "colors.smk"
include: rules_dir + "what-to-cite.smk"
include: rules_dir + "tax-search.smk"
include: rules_dir + "config.smk"

default_config = json.loads(open("../gui/default-config.json", "r", encoding="utf-8").read())
config = Config(config, default_config)     # extend config with default values

config["dir"] = str(config["dir"])
modules = []

# Manage project path
try:
    uploads_dir_relative = config["uploads_dir_rel"]
    uploads_dir_absolute = config["uploads_dir_abs"]
except KeyError:
    uploads_dir_relative = "../gui/uploads/"
    uploads_dir_absolute = "/opt/mosga/gui/uploads/"
target_dir = absolute_dir + uploads_dir_relative + config["dir"]
log_dir = target_dir + "/logs"

# Create log dir if not existing (PHP)
try:
    os.makedirs(log_dir)
except OSError as e:
    pass

# Backwards compatibility (MOSGA v1)
try:
    pipe = config["mode"]
except KeyError:
    pipe = "annotation"

# Load gui rules
gui = json.loads(open("../gui/gui-rules.json", "r", encoding="utf-8").read())

# Load citation methods and add default citations
cite = WhatToCite(target_dir + "/what-to-cite.txt")
cite.add(publications["mosga"])
cite.add(publications["mosga2"])

# Enable taxonomy search
tax = TaxonomySearch("../data/tax/taxonomy.json", "../data/tax/tax-tools.json", config)

# Gene Codes
nuclear_gene_code = 1
mito_gene_code = 1
plastid_gene_code = 11
if tax.doSearch:
    try:
        nuclear_gene_code = GeneticCode.codes[tax.find(GeneticCode.nuclear,name="GeneCodeNuclear")]
        mito_gene_code = GeneticCode.codes[tax.find(GeneticCode.mito,name="GeneCodeMito")]
        plastid_gene_code = GeneticCode.codes[tax.find(GeneticCode.plastid,name="GeneCodePlastid")]
    except KeyError:
        pass

# genome annotation pipeline
if pipe == "annotation":
    include: rules_dir + "annotation.smk"

# genome comparative pipeline
if pipe == "comparative":
    include: rules_dir + "comparative.smk"

# Run all predictions
rule all:
    input:
        jbrowse2_out if pipe == "annotation" else[],
        file_index if pipe == "annotation" else[],
        comparative_outputs if pipe == "comparative" else [],

if tax.doSearch:
    tax.write(target_dir + "/tax-summary.html", log_dir + "/tax-summary.txt")
cite.write()
