# Copyright (C) 2023 Luigi Pertoldi <gipert@pm.me>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import os
from datetime import datetime
from pathlib import Path
import time

from snakemake.logging import logger
from dbetto import AttrsDict

from legendsimflow import aggregate, patterns, utils, validate


logger.info("Initializing workflow context")

SIMFLOW_CONTEXT = utils.init_simflow_context(config, workflow, logger=logger)
config = SIMFLOW_CONTEXT.config

# sanitize the make_steps field
make_steps = utils.sorted_by(config.make_steps, aggregate.STEPS_ORDERED, "make_steps")
config["make_steps"] = make_steps

logger.info("Done! Handing it over to Snakemake")


wildcard_constraints:
    tier=r"\w+",
    simid=r"[-\w]+",
    jobid=r"\d+",
    runid=r"\w+(?:-\w+){3}",
    hpge_detector=r"[VPBC]\w{6}",
    hpge_voltage=r"\d+",


onstart:
    # Snakemake runs onstart also with --touch, which only updates timestamps
    if not workflow.touch:
        validate.input_paths(config)
        validate.l200data_layout(config)

    utils.setup_logdir_link(config)

    utils.link_external_paths(config, workflow.basedir, logger=logger)

    logger.info("Starting workflow")


onsuccess:
    report, n_warnings = utils.write_warnings_report(patterns.log_dirname(config))
    logger.info(f"{n_warnings} warning(s) found, report generated at {report}")


include: "rules/aux.smk"


for step in make_steps:

    include: f"rules/{step}.smk"


# strategy: select the latest requested tier (in steps_ordered),
# then make the build cumulative by including all tiers up to it.
def gen_target_all():
    if config.simlist not in ("all", "*"):
        # tuning-only production: the simlist selects the simulations the
        # impurity model is fitted on, and the model file is the only target
        if _tune_impurity:
            return [patterns.output_impurity_model_filename(config)]
        # take the modelable HPGes from the checkpoint, like the per-detector
        # rules: the metadata may have changed since the checkpoint ran
        return lambda wc: aggregate.process_simlist(
            config,
            make_steps=make_steps,
            cache=smk_load_hpge_cache() if "par" in make_steps and _simulate_psd else None,
        )

    inputs = []
    for step in make_steps:
        if step == "pdf":
            inputs.extend(rules.gen_all_tier_pdf.input)
        elif step == "cvt":
            inputs.extend(rules.gen_all_tier_cvt.input)
        elif step == "evt":
            inputs.extend(rules.gen_all_tier_evt.input)
        elif step == "hit":
            inputs.extend(rules.gen_all_tier_hit.input)
        elif step == "opt":
            inputs.extend(rules.gen_all_tier_opt.input)
        elif step == "stp":
            inputs.extend(rules.gen_all_tier_stp.input)
        elif step == "vtx":
            pass
        elif step == "par":
            inputs.extend(rules.gen_all_tier_par.input)

    # happens e.g. with make_steps=[vtx], which has no aggregate rule
    if not inputs:
        logger.warning(
            f"the default target is empty with make_steps={make_steps}: "
            "request the files you need explicitly on the command line"
        )

    return inputs


rule all:
    """Default rule.

    Makes all output files of the highest tier specified in the `make_steps`
    configuration variable (holding a list of steps) and all the simids listed
    in the `simlist` configuration variable.
    """
    default_target: True
    input:
        gen_target_all(),
