import os
import yaml
import shutil

from pathlib import Path
from snakemake.logging import logger
from snakemake.shell import shell


def bookkeep_inputs(workflow, config):
    """
    Bookkeeping function to for the inputs. Stores:
    - all input configfiles in a configfiles directory
    - a config.yaml file that contains the dump of the config dictionnary
    - input_runs_list which contains the runs list used if any provided
    - git_commit which contains a trace of the currently use commit
    - a symlink to the snakemake log file
    """

    log_file = Path(workflow.logger_manager.get_logfile()[0])
    output_path = Path(f"bookkeeping/inputs/{log_file.name.split('.')[0]}/")

    if output_path.exists():
        raise Exception("{output_path} already exists!!")

    output_path.mkdir(parents=True)

    # Create a symlink to log file
    (output_path / "log_file").symlink_to(log_file)

    # Export configuration files
    output_path_configfiles = output_path / "configfiles"
    output_path_configfiles.mkdir()
    for configfile in workflow.configfiles:
        shutil.copy(configfile, output_path_configfiles)

    # Export effective configuration
    with open(output_path / "config.yaml", "w") as yaml_file:
        yaml.dump(config, yaml_file)

    # Export runs_list
    if "runs_list" in config:
        shutil.copy(config["runs_list"], output_path / "input_runs_list")

    # Export the git commit from rbdp repo
    git_trace = output_path / "git_commit"
    shell(f"git -C {workflow.basedir} describe --dirty --always --long > {git_trace}")

    logger.info(f"Inputs bookkeeping done in {output_path}")
