import os
from snakemake.logging import logger
from snakemake_interface_executor_plugins.settings import DeploymentMethod


def default(workflow):
    set_apptainer_args(workflow)
    set_default_ressources(workflow)
    set_default_cache_directory(workflow)


def set_apptainer_args(workflow):
    """
    Set apptainer arguments for the workflow
    """
    #  - Force the use of apptainer
    workflow.deployment_settings.deployment_method.add(DeploymentMethod.APPTAINER)

    #  - Using apptainer, does not export host environment
    workflow.deployment_settings.apptainer_args += " --cleanenv"
    #  - Export proxy variables if sets:
    if "http_proxy" in os.environ:
        workflow.deployment_settings.apptainer_args += (
            " --env http_proxy=" + os.environ["http_proxy"]
        )
    if "https_proxy" in os.environ:
        workflow.deployment_settings.apptainer_args += (
            " --env https_proxy=" + os.environ["https_proxy"]
        )

    # For some reason, if only one arg is provided we need quotes
    # if " " not in workflow.deployment_settings.apptainer_args:
    #     workflow.deployment_settings.apptainer_args = (
    #         '"' + workflow.deployment_settings.apptainer_args + '"'
    #     )


def set_default_ressources(workflow):
    """If not manually set, fix limit on ressources"""

    # Only set resources from the steering process
    if not workflow.is_main_process:
        return

    # If not manually set, limit irods/xrootd/km3db to 5e simultaneous jobs
    if "irods_socket" not in workflow.global_resources:
        workflow.global_resources["irods_socket"] = 5
    if "xrootd_socket" not in workflow.global_resources:
        workflow.global_resources["xrootd_socket"] = 5
    if "km3net_db_socket" not in workflow.global_resources:
        workflow.global_resources["km3net_db_socket"] = 5


def set_default_cache_directory(workflow):
    """set XDG_CACHE_HOME, where sources are cached, to point in workdir"""
    if "XDG_CACHE_HOME" not in os.environ:
        os.environ["XDG_CACHE_HOME"] = f"{workflow.workdir_init}/.snakemake_cache"
        logger.info(f"Set XDG_CACHE_HOME to {os.environ['XDG_CACHE_HOME']}")
    else:
        logger.info(f"XDG_CACHE_HOME already set to {os.environ['XDG_CACHE_HOME']}")
